es6.js 4.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738
  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. * @returns the new sliced array
  7913. */
  7914. Tools.Slice = function (data) {
  7915. if (data.slice) {
  7916. return data.slice();
  7917. }
  7918. return Array.prototype.slice.call(data);
  7919. };
  7920. Tools.SetImmediate = function (action) {
  7921. if (window.setImmediate) {
  7922. window.setImmediate(action);
  7923. }
  7924. else {
  7925. setTimeout(action, 1);
  7926. }
  7927. };
  7928. Tools.IsExponentOfTwo = function (value) {
  7929. var count = 1;
  7930. do {
  7931. count *= 2;
  7932. } while (count < value);
  7933. return count === value;
  7934. };
  7935. /**
  7936. * Find the next highest power of two.
  7937. * @param x Number to start search from.
  7938. * @return Next highest power of two.
  7939. */
  7940. Tools.CeilingPOT = function (x) {
  7941. x--;
  7942. x |= x >> 1;
  7943. x |= x >> 2;
  7944. x |= x >> 4;
  7945. x |= x >> 8;
  7946. x |= x >> 16;
  7947. x++;
  7948. return x;
  7949. };
  7950. /**
  7951. * Find the next lowest power of two.
  7952. * @param x Number to start search from.
  7953. * @return Next lowest power of two.
  7954. */
  7955. Tools.FloorPOT = function (x) {
  7956. x = x | (x >> 1);
  7957. x = x | (x >> 2);
  7958. x = x | (x >> 4);
  7959. x = x | (x >> 8);
  7960. x = x | (x >> 16);
  7961. return x - (x >> 1);
  7962. };
  7963. /**
  7964. * Find the nearest power of two.
  7965. * @param x Number to start search from.
  7966. * @return Next nearest power of two.
  7967. */
  7968. Tools.NearestPOT = function (x) {
  7969. var c = Tools.CeilingPOT(x);
  7970. var f = Tools.FloorPOT(x);
  7971. return (c - x) > (x - f) ? f : c;
  7972. };
  7973. Tools.GetExponentOfTwo = function (value, max, mode) {
  7974. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7975. var pot;
  7976. switch (mode) {
  7977. case BABYLON.Engine.SCALEMODE_FLOOR:
  7978. pot = Tools.FloorPOT(value);
  7979. break;
  7980. case BABYLON.Engine.SCALEMODE_NEAREST:
  7981. pot = Tools.NearestPOT(value);
  7982. break;
  7983. case BABYLON.Engine.SCALEMODE_CEILING:
  7984. default:
  7985. pot = Tools.CeilingPOT(value);
  7986. break;
  7987. }
  7988. return Math.min(pot, max);
  7989. };
  7990. Tools.GetFilename = function (path) {
  7991. var index = path.lastIndexOf("/");
  7992. if (index < 0)
  7993. return path;
  7994. return path.substring(index + 1);
  7995. };
  7996. /**
  7997. * Extracts the "folder" part of a path (everything before the filename).
  7998. * @param uri The URI to extract the info from
  7999. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8000. * @returns The "folder" part of the path
  8001. */
  8002. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8003. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8004. var index = uri.lastIndexOf("/");
  8005. if (index < 0) {
  8006. if (returnUnchangedIfNoSlash) {
  8007. return uri;
  8008. }
  8009. return "";
  8010. }
  8011. return uri.substring(0, index + 1);
  8012. };
  8013. Tools.GetDOMTextContent = function (element) {
  8014. var result = "";
  8015. var child = element.firstChild;
  8016. while (child) {
  8017. if (child.nodeType === 3) {
  8018. result += child.textContent;
  8019. }
  8020. child = child.nextSibling;
  8021. }
  8022. return result;
  8023. };
  8024. Tools.ToDegrees = function (angle) {
  8025. return angle * 180 / Math.PI;
  8026. };
  8027. Tools.ToRadians = function (angle) {
  8028. return angle * Math.PI / 180;
  8029. };
  8030. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8031. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8032. var output = "";
  8033. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8034. var i = 0;
  8035. var bytes = new Uint8Array(buffer);
  8036. while (i < bytes.length) {
  8037. chr1 = bytes[i++];
  8038. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8039. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8040. enc1 = chr1 >> 2;
  8041. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8042. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8043. enc4 = chr3 & 63;
  8044. if (isNaN(chr2)) {
  8045. enc3 = enc4 = 64;
  8046. }
  8047. else if (isNaN(chr3)) {
  8048. enc4 = 64;
  8049. }
  8050. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8051. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8052. }
  8053. return "data:image/png;base64," + output;
  8054. };
  8055. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8056. if (bias === void 0) { bias = null; }
  8057. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8058. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8059. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8060. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8061. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8062. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8063. }
  8064. if (bias) {
  8065. minimum.x -= minimum.x * bias.x + bias.y;
  8066. minimum.y -= minimum.y * bias.x + bias.y;
  8067. minimum.z -= minimum.z * bias.x + bias.y;
  8068. maximum.x += maximum.x * bias.x + bias.y;
  8069. maximum.y += maximum.y * bias.x + bias.y;
  8070. maximum.z += maximum.z * bias.x + bias.y;
  8071. }
  8072. return {
  8073. minimum: minimum,
  8074. maximum: maximum
  8075. };
  8076. };
  8077. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8078. if (bias === void 0) { bias = null; }
  8079. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8080. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8081. if (!stride) {
  8082. stride = 3;
  8083. }
  8084. for (var index = start; index < start + count; index++) {
  8085. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8086. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8087. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8088. }
  8089. if (bias) {
  8090. minimum.x -= minimum.x * bias.x + bias.y;
  8091. minimum.y -= minimum.y * bias.x + bias.y;
  8092. minimum.z -= minimum.z * bias.x + bias.y;
  8093. maximum.x += maximum.x * bias.x + bias.y;
  8094. maximum.y += maximum.y * bias.x + bias.y;
  8095. maximum.z += maximum.z * bias.x + bias.y;
  8096. }
  8097. return {
  8098. minimum: minimum,
  8099. maximum: maximum
  8100. };
  8101. };
  8102. Tools.Vector2ArrayFeeder = function (array) {
  8103. return function (index) {
  8104. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8105. var length = isFloatArray ? array.length / 2 : array.length;
  8106. if (index >= length) {
  8107. return null;
  8108. }
  8109. if (isFloatArray) {
  8110. var fa = array;
  8111. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8112. }
  8113. var a = array;
  8114. return a[index];
  8115. };
  8116. };
  8117. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8118. if (bias === void 0) { bias = null; }
  8119. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8120. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8121. var i = 0;
  8122. var cur = feeder(i++);
  8123. while (cur) {
  8124. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8125. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8126. cur = feeder(i++);
  8127. }
  8128. if (bias) {
  8129. minimum.x -= minimum.x * bias.x + bias.y;
  8130. minimum.y -= minimum.y * bias.x + bias.y;
  8131. maximum.x += maximum.x * bias.x + bias.y;
  8132. maximum.y += maximum.y * bias.x + bias.y;
  8133. }
  8134. return {
  8135. minimum: minimum,
  8136. maximum: maximum
  8137. };
  8138. };
  8139. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8140. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8141. return null;
  8142. return Array.isArray(obj) ? obj : [obj];
  8143. };
  8144. // Misc.
  8145. Tools.GetPointerPrefix = function () {
  8146. var eventPrefix = "pointer";
  8147. // Check if pointer events are supported
  8148. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8149. eventPrefix = "mouse";
  8150. }
  8151. return eventPrefix;
  8152. };
  8153. /**
  8154. * @param func - the function to be called
  8155. * @param requester - the object that will request the next frame. Falls back to window.
  8156. */
  8157. Tools.QueueNewFrame = function (func, requester) {
  8158. if (!Tools.IsWindowObjectExist()) {
  8159. return setTimeout(func, 16);
  8160. }
  8161. if (!requester) {
  8162. requester = window;
  8163. }
  8164. if (requester.requestAnimationFrame) {
  8165. return requester.requestAnimationFrame(func);
  8166. }
  8167. else if (requester.msRequestAnimationFrame) {
  8168. return requester.msRequestAnimationFrame(func);
  8169. }
  8170. else if (requester.webkitRequestAnimationFrame) {
  8171. return requester.webkitRequestAnimationFrame(func);
  8172. }
  8173. else if (requester.mozRequestAnimationFrame) {
  8174. return requester.mozRequestAnimationFrame(func);
  8175. }
  8176. else if (requester.oRequestAnimationFrame) {
  8177. return requester.oRequestAnimationFrame(func);
  8178. }
  8179. else {
  8180. return window.setTimeout(func, 16);
  8181. }
  8182. };
  8183. Tools.RequestFullscreen = function (element) {
  8184. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8185. if (!requestFunction)
  8186. return;
  8187. requestFunction.call(element);
  8188. };
  8189. Tools.ExitFullscreen = function () {
  8190. if (document.exitFullscreen) {
  8191. document.exitFullscreen();
  8192. }
  8193. else if (document.mozCancelFullScreen) {
  8194. document.mozCancelFullScreen();
  8195. }
  8196. else if (document.webkitCancelFullScreen) {
  8197. document.webkitCancelFullScreen();
  8198. }
  8199. else if (document.msCancelFullScreen) {
  8200. document.msCancelFullScreen();
  8201. }
  8202. };
  8203. Tools.SetCorsBehavior = function (url, element) {
  8204. if (url && url.indexOf("data:") === 0) {
  8205. return;
  8206. }
  8207. if (Tools.CorsBehavior) {
  8208. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8209. element.crossOrigin = Tools.CorsBehavior;
  8210. }
  8211. else {
  8212. var result = Tools.CorsBehavior(url);
  8213. if (result) {
  8214. element.crossOrigin = result;
  8215. }
  8216. }
  8217. }
  8218. };
  8219. // External files
  8220. Tools.CleanUrl = function (url) {
  8221. url = url.replace(/#/mg, "%23");
  8222. return url;
  8223. };
  8224. Tools.LoadImage = function (url, onLoad, onError, database) {
  8225. if (url instanceof ArrayBuffer) {
  8226. url = Tools.EncodeArrayBufferTobase64(url);
  8227. }
  8228. url = Tools.CleanUrl(url);
  8229. url = Tools.PreprocessUrl(url);
  8230. var img = new Image();
  8231. Tools.SetCorsBehavior(url, img);
  8232. var loadHandler = function () {
  8233. img.removeEventListener("load", loadHandler);
  8234. img.removeEventListener("error", errorHandler);
  8235. onLoad(img);
  8236. };
  8237. var errorHandler = function (err) {
  8238. img.removeEventListener("load", loadHandler);
  8239. img.removeEventListener("error", errorHandler);
  8240. Tools.Error("Error while trying to load image: " + url);
  8241. if (onError) {
  8242. onError("Error while trying to load image: " + url, err);
  8243. }
  8244. };
  8245. img.addEventListener("load", loadHandler);
  8246. img.addEventListener("error", errorHandler);
  8247. var noIndexedDB = function () {
  8248. img.src = url;
  8249. };
  8250. var loadFromIndexedDB = function () {
  8251. if (database) {
  8252. database.loadImageFromDB(url, img);
  8253. }
  8254. };
  8255. //ANY database to do!
  8256. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8257. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8258. }
  8259. else {
  8260. if (url.indexOf("file:") !== -1) {
  8261. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8262. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8263. try {
  8264. var blobURL;
  8265. try {
  8266. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8267. }
  8268. catch (ex) {
  8269. // Chrome doesn't support oneTimeOnly parameter
  8270. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8271. }
  8272. img.src = blobURL;
  8273. }
  8274. catch (e) {
  8275. img.src = "";
  8276. }
  8277. return img;
  8278. }
  8279. }
  8280. noIndexedDB();
  8281. }
  8282. return img;
  8283. };
  8284. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8285. url = Tools.CleanUrl(url);
  8286. url = Tools.PreprocessUrl(url);
  8287. // If file and file input are set
  8288. if (url.indexOf("file:") !== -1) {
  8289. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8290. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8291. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8292. }
  8293. }
  8294. var loadUrl = Tools.BaseUrl + url;
  8295. var aborted = false;
  8296. var fileRequest = {
  8297. onCompleteObservable: new BABYLON.Observable(),
  8298. abort: function () { return aborted = true; },
  8299. };
  8300. var requestFile = function () {
  8301. var request = new XMLHttpRequest();
  8302. var retryHandle = null;
  8303. fileRequest.abort = function () {
  8304. aborted = true;
  8305. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8306. request.abort();
  8307. }
  8308. if (retryHandle !== null) {
  8309. clearTimeout(retryHandle);
  8310. retryHandle = null;
  8311. }
  8312. };
  8313. var retryLoop = function (retryIndex) {
  8314. request.open('GET', loadUrl, true);
  8315. if (useArrayBuffer) {
  8316. request.responseType = "arraybuffer";
  8317. }
  8318. if (onProgress) {
  8319. request.addEventListener("progress", onProgress);
  8320. }
  8321. var onLoadEnd = function () {
  8322. request.removeEventListener("loadend", onLoadEnd);
  8323. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8324. fileRequest.onCompleteObservable.clear();
  8325. };
  8326. request.addEventListener("loadend", onLoadEnd);
  8327. var onReadyStateChange = function () {
  8328. if (aborted) {
  8329. return;
  8330. }
  8331. // In case of undefined state in some browsers.
  8332. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8333. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8334. request.removeEventListener("readystatechange", onReadyStateChange);
  8335. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8336. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8337. return;
  8338. }
  8339. var retryStrategy = Tools.DefaultRetryStrategy;
  8340. if (retryStrategy) {
  8341. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8342. if (waitTime !== -1) {
  8343. // Prevent the request from completing for retry.
  8344. request.removeEventListener("loadend", onLoadEnd);
  8345. request = new XMLHttpRequest();
  8346. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8347. return;
  8348. }
  8349. }
  8350. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8351. if (onError) {
  8352. onError(request, e);
  8353. }
  8354. else {
  8355. throw e;
  8356. }
  8357. }
  8358. };
  8359. request.addEventListener("readystatechange", onReadyStateChange);
  8360. request.send();
  8361. };
  8362. retryLoop(0);
  8363. };
  8364. // Caching all files
  8365. if (database && database.enableSceneOffline) {
  8366. var noIndexedDB_1 = function () {
  8367. if (!aborted) {
  8368. requestFile();
  8369. }
  8370. };
  8371. var loadFromIndexedDB = function () {
  8372. // TODO: database needs to support aborting and should return a IFileRequest
  8373. if (aborted) {
  8374. return;
  8375. }
  8376. if (database) {
  8377. database.loadFileFromDB(url, function (data) {
  8378. if (!aborted) {
  8379. onSuccess(data);
  8380. }
  8381. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8382. }, onProgress ? function (event) {
  8383. if (!aborted) {
  8384. onProgress(event);
  8385. }
  8386. } : undefined, noIndexedDB_1, useArrayBuffer);
  8387. }
  8388. };
  8389. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8390. }
  8391. else {
  8392. requestFile();
  8393. }
  8394. return fileRequest;
  8395. };
  8396. /**
  8397. * Load a script (identified by an url). When the url returns, the
  8398. * content of this file is added into a new script element, attached to the DOM (body element)
  8399. */
  8400. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8401. var head = document.getElementsByTagName('head')[0];
  8402. var script = document.createElement('script');
  8403. script.type = 'text/javascript';
  8404. script.src = scriptUrl;
  8405. script.onload = function () {
  8406. if (onSuccess) {
  8407. onSuccess();
  8408. }
  8409. };
  8410. script.onerror = function (e) {
  8411. if (onError) {
  8412. onError("Unable to load script", e);
  8413. }
  8414. };
  8415. head.appendChild(script);
  8416. };
  8417. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8418. var reader = new FileReader();
  8419. var request = {
  8420. onCompleteObservable: new BABYLON.Observable(),
  8421. abort: function () { return reader.abort(); },
  8422. };
  8423. reader.onloadend = function (e) {
  8424. request.onCompleteObservable.notifyObservers(request);
  8425. };
  8426. reader.onload = function (e) {
  8427. //target doesn't have result from ts 1.3
  8428. callback(e.target['result']);
  8429. };
  8430. reader.onprogress = progressCallback;
  8431. reader.readAsDataURL(fileToLoad);
  8432. return request;
  8433. };
  8434. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8435. var reader = new FileReader();
  8436. var request = {
  8437. onCompleteObservable: new BABYLON.Observable(),
  8438. abort: function () { return reader.abort(); },
  8439. };
  8440. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8441. reader.onerror = function (e) {
  8442. Tools.Log("Error while reading file: " + fileToLoad.name);
  8443. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8444. };
  8445. reader.onload = function (e) {
  8446. //target doesn't have result from ts 1.3
  8447. callback(e.target['result']);
  8448. };
  8449. if (progressCallBack) {
  8450. reader.onprogress = progressCallBack;
  8451. }
  8452. if (!useArrayBuffer) {
  8453. // Asynchronous read
  8454. reader.readAsText(fileToLoad);
  8455. }
  8456. else {
  8457. reader.readAsArrayBuffer(fileToLoad);
  8458. }
  8459. return request;
  8460. };
  8461. //returns a downloadable url to a file content.
  8462. Tools.FileAsURL = function (content) {
  8463. var fileBlob = new Blob([content]);
  8464. var url = window.URL || window.webkitURL;
  8465. var link = url.createObjectURL(fileBlob);
  8466. return link;
  8467. };
  8468. // Misc.
  8469. Tools.Format = function (value, decimals) {
  8470. if (decimals === void 0) { decimals = 2; }
  8471. return value.toFixed(decimals);
  8472. };
  8473. Tools.CheckExtends = function (v, min, max) {
  8474. if (v.x < min.x)
  8475. min.x = v.x;
  8476. if (v.y < min.y)
  8477. min.y = v.y;
  8478. if (v.z < min.z)
  8479. min.z = v.z;
  8480. if (v.x > max.x)
  8481. max.x = v.x;
  8482. if (v.y > max.y)
  8483. max.y = v.y;
  8484. if (v.z > max.z)
  8485. max.z = v.z;
  8486. };
  8487. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8488. for (var prop in source) {
  8489. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8490. continue;
  8491. }
  8492. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8493. continue;
  8494. }
  8495. var sourceValue = source[prop];
  8496. var typeOfSourceValue = typeof sourceValue;
  8497. if (typeOfSourceValue === "function") {
  8498. continue;
  8499. }
  8500. try {
  8501. if (typeOfSourceValue === "object") {
  8502. if (sourceValue instanceof Array) {
  8503. destination[prop] = [];
  8504. if (sourceValue.length > 0) {
  8505. if (typeof sourceValue[0] == "object") {
  8506. for (var index = 0; index < sourceValue.length; index++) {
  8507. var clonedValue = cloneValue(sourceValue[index], destination);
  8508. if (destination[prop].indexOf(clonedValue) === -1) {
  8509. destination[prop].push(clonedValue);
  8510. }
  8511. }
  8512. }
  8513. else {
  8514. destination[prop] = sourceValue.slice(0);
  8515. }
  8516. }
  8517. }
  8518. else {
  8519. destination[prop] = cloneValue(sourceValue, destination);
  8520. }
  8521. }
  8522. else {
  8523. destination[prop] = sourceValue;
  8524. }
  8525. }
  8526. catch (e) {
  8527. // Just ignore error (it could be because of a read-only property)
  8528. }
  8529. }
  8530. };
  8531. Tools.IsEmpty = function (obj) {
  8532. for (var i in obj) {
  8533. if (obj.hasOwnProperty(i)) {
  8534. return false;
  8535. }
  8536. }
  8537. return true;
  8538. };
  8539. Tools.RegisterTopRootEvents = function (events) {
  8540. for (var index = 0; index < events.length; index++) {
  8541. var event = events[index];
  8542. window.addEventListener(event.name, event.handler, false);
  8543. try {
  8544. if (window.parent) {
  8545. window.parent.addEventListener(event.name, event.handler, false);
  8546. }
  8547. }
  8548. catch (e) {
  8549. // Silently fails...
  8550. }
  8551. }
  8552. };
  8553. Tools.UnregisterTopRootEvents = function (events) {
  8554. for (var index = 0; index < events.length; index++) {
  8555. var event = events[index];
  8556. window.removeEventListener(event.name, event.handler);
  8557. try {
  8558. if (window.parent) {
  8559. window.parent.removeEventListener(event.name, event.handler);
  8560. }
  8561. }
  8562. catch (e) {
  8563. // Silently fails...
  8564. }
  8565. }
  8566. };
  8567. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8568. if (mimeType === void 0) { mimeType = "image/png"; }
  8569. // Read the contents of the framebuffer
  8570. var numberOfChannelsByLine = width * 4;
  8571. var halfHeight = height / 2;
  8572. //Reading datas from WebGL
  8573. var data = engine.readPixels(0, 0, width, height);
  8574. //To flip image on Y axis.
  8575. for (var i = 0; i < halfHeight; i++) {
  8576. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8577. var currentCell = j + i * numberOfChannelsByLine;
  8578. var targetLine = height - i - 1;
  8579. var targetCell = j + targetLine * numberOfChannelsByLine;
  8580. var temp = data[currentCell];
  8581. data[currentCell] = data[targetCell];
  8582. data[targetCell] = temp;
  8583. }
  8584. }
  8585. // Create a 2D canvas to store the result
  8586. if (!screenshotCanvas) {
  8587. screenshotCanvas = document.createElement('canvas');
  8588. }
  8589. screenshotCanvas.width = width;
  8590. screenshotCanvas.height = height;
  8591. var context = screenshotCanvas.getContext('2d');
  8592. if (context) {
  8593. // Copy the pixels to a 2D canvas
  8594. var imageData = context.createImageData(width, height);
  8595. var castData = (imageData.data);
  8596. castData.set(data);
  8597. context.putImageData(imageData, 0, 0);
  8598. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8599. }
  8600. };
  8601. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8602. if (mimeType === void 0) { mimeType = "image/png"; }
  8603. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8604. if (successCallback) {
  8605. successCallback(base64Image);
  8606. }
  8607. else {
  8608. // We need HTMLCanvasElement.toBlob for HD screenshots
  8609. if (!screenshotCanvas.toBlob) {
  8610. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8611. screenshotCanvas.toBlob = function (callback, type, quality) {
  8612. var _this = this;
  8613. setTimeout(function () {
  8614. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8615. for (var i = 0; i < len; i++) {
  8616. arr[i] = binStr.charCodeAt(i);
  8617. }
  8618. callback(new Blob([arr], { type: type || 'image/png' }));
  8619. });
  8620. };
  8621. }
  8622. screenshotCanvas.toBlob(function (blob) {
  8623. var url = URL.createObjectURL(blob);
  8624. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8625. if (("download" in document.createElement("a"))) {
  8626. var a = window.document.createElement("a");
  8627. a.href = url;
  8628. if (fileName) {
  8629. a.setAttribute("download", fileName);
  8630. }
  8631. else {
  8632. var date = new Date();
  8633. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8634. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8635. }
  8636. window.document.body.appendChild(a);
  8637. a.addEventListener("click", function () {
  8638. if (a.parentElement) {
  8639. a.parentElement.removeChild(a);
  8640. }
  8641. });
  8642. a.click();
  8643. }
  8644. else {
  8645. var newWindow = window.open("");
  8646. if (!newWindow)
  8647. return;
  8648. var img = newWindow.document.createElement("img");
  8649. img.onload = function () {
  8650. // no longer need to read the blob so it's revoked
  8651. URL.revokeObjectURL(url);
  8652. };
  8653. img.src = url;
  8654. newWindow.document.body.appendChild(img);
  8655. }
  8656. });
  8657. }
  8658. };
  8659. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8660. if (mimeType === void 0) { mimeType = "image/png"; }
  8661. var width;
  8662. var height;
  8663. // If a precision value is specified
  8664. if (size.precision) {
  8665. width = Math.round(engine.getRenderWidth() * size.precision);
  8666. height = Math.round(width / engine.getAspectRatio(camera));
  8667. }
  8668. else if (size.width && size.height) {
  8669. width = size.width;
  8670. height = size.height;
  8671. }
  8672. else if (size.width && !size.height) {
  8673. width = size.width;
  8674. height = Math.round(width / engine.getAspectRatio(camera));
  8675. }
  8676. else if (size.height && !size.width) {
  8677. height = size.height;
  8678. width = Math.round(height * engine.getAspectRatio(camera));
  8679. }
  8680. else if (!isNaN(size)) {
  8681. height = size;
  8682. width = size;
  8683. }
  8684. else {
  8685. Tools.Error("Invalid 'size' parameter !");
  8686. return;
  8687. }
  8688. if (!screenshotCanvas) {
  8689. screenshotCanvas = document.createElement('canvas');
  8690. }
  8691. screenshotCanvas.width = width;
  8692. screenshotCanvas.height = height;
  8693. var renderContext = screenshotCanvas.getContext("2d");
  8694. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8695. var newWidth = width;
  8696. var newHeight = newWidth / ratio;
  8697. if (newHeight > height) {
  8698. newHeight = height;
  8699. newWidth = newHeight * ratio;
  8700. }
  8701. var offsetX = Math.max(0, width - newWidth) / 2;
  8702. var offsetY = Math.max(0, height - newHeight) / 2;
  8703. var renderingCanvas = engine.getRenderingCanvas();
  8704. if (renderContext && renderingCanvas) {
  8705. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8706. }
  8707. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8708. };
  8709. /**
  8710. * Generates an image screenshot from the specified camera.
  8711. *
  8712. * @param engine The engine to use for rendering
  8713. * @param camera The camera to use for rendering
  8714. * @param size This parameter can be set to a single number or to an object with the
  8715. * following (optional) properties: precision, width, height. If a single number is passed,
  8716. * it will be used for both width and height. If an object is passed, the screenshot size
  8717. * will be derived from the parameters. The precision property is a multiplier allowing
  8718. * rendering at a higher or lower resolution.
  8719. * @param successCallback The callback receives a single parameter which contains the
  8720. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8721. * src parameter of an <img> to display it.
  8722. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8723. * Check your browser for supported MIME types.
  8724. * @param samples Texture samples (default: 1)
  8725. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8726. * @param fileName A name for for the downloaded file.
  8727. * @constructor
  8728. */
  8729. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8730. if (mimeType === void 0) { mimeType = "image/png"; }
  8731. if (samples === void 0) { samples = 1; }
  8732. if (antialiasing === void 0) { antialiasing = false; }
  8733. var width;
  8734. var height;
  8735. //If a precision value is specified
  8736. if (size.precision) {
  8737. width = Math.round(engine.getRenderWidth() * size.precision);
  8738. height = Math.round(width / engine.getAspectRatio(camera));
  8739. size = { width: width, height: height };
  8740. }
  8741. else if (size.width && size.height) {
  8742. width = size.width;
  8743. height = size.height;
  8744. }
  8745. else if (size.width && !size.height) {
  8746. width = size.width;
  8747. height = Math.round(width / engine.getAspectRatio(camera));
  8748. size = { width: width, height: height };
  8749. }
  8750. else if (size.height && !size.width) {
  8751. height = size.height;
  8752. width = Math.round(height * engine.getAspectRatio(camera));
  8753. size = { width: width, height: height };
  8754. }
  8755. else if (!isNaN(size)) {
  8756. height = size;
  8757. width = size;
  8758. }
  8759. else {
  8760. Tools.Error("Invalid 'size' parameter !");
  8761. return;
  8762. }
  8763. var scene = camera.getScene();
  8764. var previousCamera = null;
  8765. if (scene.activeCamera !== camera) {
  8766. previousCamera = scene.activeCamera;
  8767. scene.activeCamera = camera;
  8768. }
  8769. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8770. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8771. texture.renderList = null;
  8772. texture.samples = samples;
  8773. if (antialiasing) {
  8774. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8775. }
  8776. texture.onAfterRenderObservable.add(function () {
  8777. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8778. });
  8779. scene.incrementRenderId();
  8780. scene.resetCachedMaterial();
  8781. texture.render(true);
  8782. texture.dispose();
  8783. if (previousCamera) {
  8784. scene.activeCamera = previousCamera;
  8785. }
  8786. camera.getProjectionMatrix(true); // Force cache refresh;
  8787. };
  8788. // XHR response validator for local file scenario
  8789. Tools.ValidateXHRData = function (xhr, dataType) {
  8790. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8791. if (dataType === void 0) { dataType = 7; }
  8792. try {
  8793. if (dataType & 1) {
  8794. if (xhr.responseText && xhr.responseText.length > 0) {
  8795. return true;
  8796. }
  8797. else if (dataType === 1) {
  8798. return false;
  8799. }
  8800. }
  8801. if (dataType & 2) {
  8802. // Check header width and height since there is no "TGA" magic number
  8803. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8804. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8805. return true;
  8806. }
  8807. else if (dataType === 2) {
  8808. return false;
  8809. }
  8810. }
  8811. if (dataType & 4) {
  8812. // Check for the "DDS" magic number
  8813. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8814. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8815. return true;
  8816. }
  8817. else {
  8818. return false;
  8819. }
  8820. }
  8821. }
  8822. catch (e) {
  8823. // Global protection
  8824. }
  8825. return false;
  8826. };
  8827. /**
  8828. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8829. * Be aware Math.random() could cause collisions, but:
  8830. * "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"
  8831. */
  8832. Tools.RandomId = function () {
  8833. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8834. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8835. return v.toString(16);
  8836. });
  8837. };
  8838. /**
  8839. * Test if the given uri is a base64 string.
  8840. * @param uri The uri to test
  8841. * @return True if the uri is a base64 string or false otherwise.
  8842. */
  8843. Tools.IsBase64 = function (uri) {
  8844. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8845. };
  8846. /**
  8847. * Decode the given base64 uri.
  8848. * @param uri The uri to decode
  8849. * @return The decoded base64 data.
  8850. */
  8851. Tools.DecodeBase64 = function (uri) {
  8852. var decodedString = atob(uri.split(",")[1]);
  8853. var bufferLength = decodedString.length;
  8854. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8855. for (var i = 0; i < bufferLength; i++) {
  8856. bufferView[i] = decodedString.charCodeAt(i);
  8857. }
  8858. return bufferView.buffer;
  8859. };
  8860. Object.defineProperty(Tools, "NoneLogLevel", {
  8861. get: function () {
  8862. return Tools._NoneLogLevel;
  8863. },
  8864. enumerable: true,
  8865. configurable: true
  8866. });
  8867. Object.defineProperty(Tools, "MessageLogLevel", {
  8868. get: function () {
  8869. return Tools._MessageLogLevel;
  8870. },
  8871. enumerable: true,
  8872. configurable: true
  8873. });
  8874. Object.defineProperty(Tools, "WarningLogLevel", {
  8875. get: function () {
  8876. return Tools._WarningLogLevel;
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. Object.defineProperty(Tools, "ErrorLogLevel", {
  8882. get: function () {
  8883. return Tools._ErrorLogLevel;
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(Tools, "AllLogLevel", {
  8889. get: function () {
  8890. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8891. },
  8892. enumerable: true,
  8893. configurable: true
  8894. });
  8895. Tools._AddLogEntry = function (entry) {
  8896. Tools._LogCache = entry + Tools._LogCache;
  8897. if (Tools.OnNewCacheEntry) {
  8898. Tools.OnNewCacheEntry(entry);
  8899. }
  8900. };
  8901. Tools._FormatMessage = function (message) {
  8902. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8903. var date = new Date();
  8904. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8905. };
  8906. Tools._LogDisabled = function (message) {
  8907. // nothing to do
  8908. };
  8909. Tools._LogEnabled = function (message) {
  8910. var formattedMessage = Tools._FormatMessage(message);
  8911. console.log("BJS - " + formattedMessage);
  8912. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8913. Tools._AddLogEntry(entry);
  8914. };
  8915. Tools._WarnDisabled = function (message) {
  8916. // nothing to do
  8917. };
  8918. Tools._WarnEnabled = function (message) {
  8919. var formattedMessage = Tools._FormatMessage(message);
  8920. console.warn("BJS - " + formattedMessage);
  8921. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8922. Tools._AddLogEntry(entry);
  8923. };
  8924. Tools._ErrorDisabled = function (message) {
  8925. // nothing to do
  8926. };
  8927. Tools._ErrorEnabled = function (message) {
  8928. Tools.errorsCount++;
  8929. var formattedMessage = Tools._FormatMessage(message);
  8930. console.error("BJS - " + formattedMessage);
  8931. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8932. Tools._AddLogEntry(entry);
  8933. };
  8934. Object.defineProperty(Tools, "LogCache", {
  8935. get: function () {
  8936. return Tools._LogCache;
  8937. },
  8938. enumerable: true,
  8939. configurable: true
  8940. });
  8941. Tools.ClearLogCache = function () {
  8942. Tools._LogCache = "";
  8943. Tools.errorsCount = 0;
  8944. };
  8945. Object.defineProperty(Tools, "LogLevels", {
  8946. set: function (level) {
  8947. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8948. Tools.Log = Tools._LogEnabled;
  8949. }
  8950. else {
  8951. Tools.Log = Tools._LogDisabled;
  8952. }
  8953. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8954. Tools.Warn = Tools._WarnEnabled;
  8955. }
  8956. else {
  8957. Tools.Warn = Tools._WarnDisabled;
  8958. }
  8959. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8960. Tools.Error = Tools._ErrorEnabled;
  8961. }
  8962. else {
  8963. Tools.Error = Tools._ErrorDisabled;
  8964. }
  8965. },
  8966. enumerable: true,
  8967. configurable: true
  8968. });
  8969. Tools.IsWindowObjectExist = function () {
  8970. return (typeof window) !== "undefined";
  8971. };
  8972. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8973. get: function () {
  8974. return Tools._PerformanceNoneLogLevel;
  8975. },
  8976. enumerable: true,
  8977. configurable: true
  8978. });
  8979. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8980. get: function () {
  8981. return Tools._PerformanceUserMarkLogLevel;
  8982. },
  8983. enumerable: true,
  8984. configurable: true
  8985. });
  8986. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8987. get: function () {
  8988. return Tools._PerformanceConsoleLogLevel;
  8989. },
  8990. enumerable: true,
  8991. configurable: true
  8992. });
  8993. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8994. set: function (level) {
  8995. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8996. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8997. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8998. return;
  8999. }
  9000. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9001. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9002. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9003. return;
  9004. }
  9005. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9006. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9007. },
  9008. enumerable: true,
  9009. configurable: true
  9010. });
  9011. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9012. };
  9013. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9014. };
  9015. Tools._StartUserMark = function (counterName, condition) {
  9016. if (condition === void 0) { condition = true; }
  9017. if (!Tools._performance) {
  9018. if (!Tools.IsWindowObjectExist()) {
  9019. return;
  9020. }
  9021. Tools._performance = window.performance;
  9022. }
  9023. if (!condition || !Tools._performance.mark) {
  9024. return;
  9025. }
  9026. Tools._performance.mark(counterName + "-Begin");
  9027. };
  9028. Tools._EndUserMark = function (counterName, condition) {
  9029. if (condition === void 0) { condition = true; }
  9030. if (!condition || !Tools._performance.mark) {
  9031. return;
  9032. }
  9033. Tools._performance.mark(counterName + "-End");
  9034. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9035. };
  9036. Tools._StartPerformanceConsole = function (counterName, condition) {
  9037. if (condition === void 0) { condition = true; }
  9038. if (!condition) {
  9039. return;
  9040. }
  9041. Tools._StartUserMark(counterName, condition);
  9042. if (console.time) {
  9043. console.time(counterName);
  9044. }
  9045. };
  9046. Tools._EndPerformanceConsole = function (counterName, condition) {
  9047. if (condition === void 0) { condition = true; }
  9048. if (!condition) {
  9049. return;
  9050. }
  9051. Tools._EndUserMark(counterName, condition);
  9052. if (console.time) {
  9053. console.timeEnd(counterName);
  9054. }
  9055. };
  9056. Object.defineProperty(Tools, "Now", {
  9057. get: function () {
  9058. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9059. return window.performance.now();
  9060. }
  9061. return new Date().getTime();
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. /**
  9067. * This method will return the name of the class used to create the instance of the given object.
  9068. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9069. * @param object the object to get the class name from
  9070. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9071. */
  9072. Tools.GetClassName = function (object, isType) {
  9073. if (isType === void 0) { isType = false; }
  9074. var name = null;
  9075. if (!isType && object.getClassName) {
  9076. name = object.getClassName();
  9077. }
  9078. else {
  9079. if (object instanceof Object) {
  9080. var classObj = isType ? object : Object.getPrototypeOf(object);
  9081. name = classObj.constructor["__bjsclassName__"];
  9082. }
  9083. if (!name) {
  9084. name = typeof object;
  9085. }
  9086. }
  9087. return name;
  9088. };
  9089. Tools.First = function (array, predicate) {
  9090. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9091. var el = array_1[_i];
  9092. if (predicate(el)) {
  9093. return el;
  9094. }
  9095. }
  9096. return null;
  9097. };
  9098. /**
  9099. * This method will return the name of the full name of the class, including its owning module (if any).
  9100. * 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).
  9101. * @param object the object to get the class name from
  9102. * @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.
  9103. */
  9104. Tools.getFullClassName = function (object, isType) {
  9105. if (isType === void 0) { isType = false; }
  9106. var className = null;
  9107. var moduleName = null;
  9108. if (!isType && object.getClassName) {
  9109. className = object.getClassName();
  9110. }
  9111. else {
  9112. if (object instanceof Object) {
  9113. var classObj = isType ? object : Object.getPrototypeOf(object);
  9114. className = classObj.constructor["__bjsclassName__"];
  9115. moduleName = classObj.constructor["__bjsmoduleName__"];
  9116. }
  9117. if (!className) {
  9118. className = typeof object;
  9119. }
  9120. }
  9121. if (!className) {
  9122. return null;
  9123. }
  9124. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9125. };
  9126. /**
  9127. * 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.
  9128. * @param array
  9129. */
  9130. Tools.arrayOrStringFeeder = function (array) {
  9131. return function (index) {
  9132. if (index >= array.length) {
  9133. return null;
  9134. }
  9135. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9136. if (val && val.getHashCode) {
  9137. val = val.getHashCode();
  9138. }
  9139. if (typeof val === "string") {
  9140. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9141. }
  9142. return val;
  9143. };
  9144. };
  9145. /**
  9146. * Compute the hashCode of a stream of number
  9147. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9148. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9149. * @return the hash code computed
  9150. */
  9151. Tools.hashCodeFromStream = function (feeder) {
  9152. // Based from here: http://stackoverflow.com/a/7616484/802124
  9153. var hash = 0;
  9154. var index = 0;
  9155. var chr = feeder(index++);
  9156. while (chr != null) {
  9157. hash = ((hash << 5) - hash) + chr;
  9158. hash |= 0; // Convert to 32bit integer
  9159. chr = feeder(index++);
  9160. }
  9161. return hash;
  9162. };
  9163. /**
  9164. * Returns a promise that resolves after the given amount of time.
  9165. * @param delay Number of milliseconds to delay
  9166. * @returns Promise that resolves after the given amount of time
  9167. */
  9168. Tools.DelayAsync = function (delay) {
  9169. return new Promise(function (resolve) {
  9170. setTimeout(function () {
  9171. resolve();
  9172. }, delay);
  9173. });
  9174. };
  9175. Tools.BaseUrl = "";
  9176. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9177. /**
  9178. * Default behaviour for cors in the application.
  9179. * It can be a string if the expected behavior is identical in the entire app.
  9180. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9181. */
  9182. Tools.CorsBehavior = "anonymous";
  9183. Tools.UseFallbackTexture = true;
  9184. /**
  9185. * Use this object to register external classes like custom textures or material
  9186. * to allow the laoders to instantiate them
  9187. */
  9188. Tools.RegisteredExternalClasses = {};
  9189. // Used in case of a texture loading problem
  9190. 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";
  9191. Tools.PreprocessUrl = function (url) {
  9192. return url;
  9193. };
  9194. // Logs
  9195. Tools._NoneLogLevel = 0;
  9196. Tools._MessageLogLevel = 1;
  9197. Tools._WarningLogLevel = 2;
  9198. Tools._ErrorLogLevel = 4;
  9199. Tools._LogCache = "";
  9200. Tools.errorsCount = 0;
  9201. Tools.Log = Tools._LogEnabled;
  9202. Tools.Warn = Tools._WarnEnabled;
  9203. Tools.Error = Tools._ErrorEnabled;
  9204. // Performances
  9205. Tools._PerformanceNoneLogLevel = 0;
  9206. Tools._PerformanceUserMarkLogLevel = 1;
  9207. Tools._PerformanceConsoleLogLevel = 2;
  9208. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9209. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9210. return Tools;
  9211. }());
  9212. BABYLON.Tools = Tools;
  9213. /**
  9214. * This class is used to track a performance counter which is number based.
  9215. * The user has access to many properties which give statistics of different nature
  9216. *
  9217. * The implementer can track two kinds of Performance Counter: time and count
  9218. * 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.
  9219. * 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.
  9220. */
  9221. var PerfCounter = /** @class */ (function () {
  9222. function PerfCounter() {
  9223. this._startMonitoringTime = 0;
  9224. this._min = 0;
  9225. this._max = 0;
  9226. this._average = 0;
  9227. this._lastSecAverage = 0;
  9228. this._current = 0;
  9229. this._totalValueCount = 0;
  9230. this._totalAccumulated = 0;
  9231. this._lastSecAccumulated = 0;
  9232. this._lastSecTime = 0;
  9233. this._lastSecValueCount = 0;
  9234. }
  9235. Object.defineProperty(PerfCounter.prototype, "min", {
  9236. /**
  9237. * Returns the smallest value ever
  9238. */
  9239. get: function () {
  9240. return this._min;
  9241. },
  9242. enumerable: true,
  9243. configurable: true
  9244. });
  9245. Object.defineProperty(PerfCounter.prototype, "max", {
  9246. /**
  9247. * Returns the biggest value ever
  9248. */
  9249. get: function () {
  9250. return this._max;
  9251. },
  9252. enumerable: true,
  9253. configurable: true
  9254. });
  9255. Object.defineProperty(PerfCounter.prototype, "average", {
  9256. /**
  9257. * Returns the average value since the performance counter is running
  9258. */
  9259. get: function () {
  9260. return this._average;
  9261. },
  9262. enumerable: true,
  9263. configurable: true
  9264. });
  9265. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9266. /**
  9267. * Returns the average value of the last second the counter was monitored
  9268. */
  9269. get: function () {
  9270. return this._lastSecAverage;
  9271. },
  9272. enumerable: true,
  9273. configurable: true
  9274. });
  9275. Object.defineProperty(PerfCounter.prototype, "current", {
  9276. /**
  9277. * Returns the current value
  9278. */
  9279. get: function () {
  9280. return this._current;
  9281. },
  9282. enumerable: true,
  9283. configurable: true
  9284. });
  9285. Object.defineProperty(PerfCounter.prototype, "total", {
  9286. get: function () {
  9287. return this._totalAccumulated;
  9288. },
  9289. enumerable: true,
  9290. configurable: true
  9291. });
  9292. Object.defineProperty(PerfCounter.prototype, "count", {
  9293. get: function () {
  9294. return this._totalValueCount;
  9295. },
  9296. enumerable: true,
  9297. configurable: true
  9298. });
  9299. /**
  9300. * Call this method to start monitoring a new frame.
  9301. * 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.
  9302. */
  9303. PerfCounter.prototype.fetchNewFrame = function () {
  9304. this._totalValueCount++;
  9305. this._current = 0;
  9306. this._lastSecValueCount++;
  9307. };
  9308. /**
  9309. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9310. * @param newCount the count value to add to the monitored count
  9311. * @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.
  9312. */
  9313. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9314. if (!PerfCounter.Enabled) {
  9315. return;
  9316. }
  9317. this._current += newCount;
  9318. if (fetchResult) {
  9319. this._fetchResult();
  9320. }
  9321. };
  9322. /**
  9323. * Start monitoring this performance counter
  9324. */
  9325. PerfCounter.prototype.beginMonitoring = function () {
  9326. if (!PerfCounter.Enabled) {
  9327. return;
  9328. }
  9329. this._startMonitoringTime = Tools.Now;
  9330. };
  9331. /**
  9332. * Compute the time lapsed since the previous beginMonitoring() call.
  9333. * @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
  9334. */
  9335. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9336. if (newFrame === void 0) { newFrame = true; }
  9337. if (!PerfCounter.Enabled) {
  9338. return;
  9339. }
  9340. if (newFrame) {
  9341. this.fetchNewFrame();
  9342. }
  9343. var currentTime = Tools.Now;
  9344. this._current = currentTime - this._startMonitoringTime;
  9345. if (newFrame) {
  9346. this._fetchResult();
  9347. }
  9348. };
  9349. PerfCounter.prototype._fetchResult = function () {
  9350. this._totalAccumulated += this._current;
  9351. this._lastSecAccumulated += this._current;
  9352. // Min/Max update
  9353. this._min = Math.min(this._min, this._current);
  9354. this._max = Math.max(this._max, this._current);
  9355. this._average = this._totalAccumulated / this._totalValueCount;
  9356. // Reset last sec?
  9357. var now = Tools.Now;
  9358. if ((now - this._lastSecTime) > 1000) {
  9359. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9360. this._lastSecTime = now;
  9361. this._lastSecAccumulated = 0;
  9362. this._lastSecValueCount = 0;
  9363. }
  9364. };
  9365. PerfCounter.Enabled = true;
  9366. return PerfCounter;
  9367. }());
  9368. BABYLON.PerfCounter = PerfCounter;
  9369. /**
  9370. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9371. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9372. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9373. * @param name The name of the class, case should be preserved
  9374. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9375. */
  9376. function className(name, module) {
  9377. return function (target) {
  9378. target["__bjsclassName__"] = name;
  9379. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9380. };
  9381. }
  9382. BABYLON.className = className;
  9383. /**
  9384. * An implementation of a loop for asynchronous functions.
  9385. */
  9386. var AsyncLoop = /** @class */ (function () {
  9387. /**
  9388. * Constroctor.
  9389. * @param iterations the number of iterations.
  9390. * @param _fn the function to run each iteration
  9391. * @param _successCallback the callback that will be called upon succesful execution
  9392. * @param offset starting offset.
  9393. */
  9394. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9395. if (offset === void 0) { offset = 0; }
  9396. this.iterations = iterations;
  9397. this._fn = _fn;
  9398. this._successCallback = _successCallback;
  9399. this.index = offset - 1;
  9400. this._done = false;
  9401. }
  9402. /**
  9403. * Execute the next iteration. Must be called after the last iteration was finished.
  9404. */
  9405. AsyncLoop.prototype.executeNext = function () {
  9406. if (!this._done) {
  9407. if (this.index + 1 < this.iterations) {
  9408. ++this.index;
  9409. this._fn(this);
  9410. }
  9411. else {
  9412. this.breakLoop();
  9413. }
  9414. }
  9415. };
  9416. /**
  9417. * Break the loop and run the success callback.
  9418. */
  9419. AsyncLoop.prototype.breakLoop = function () {
  9420. this._done = true;
  9421. this._successCallback();
  9422. };
  9423. /**
  9424. * Helper function
  9425. */
  9426. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9427. if (offset === void 0) { offset = 0; }
  9428. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9429. loop.executeNext();
  9430. return loop;
  9431. };
  9432. /**
  9433. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9434. * @param iterations total number of iterations
  9435. * @param syncedIterations number of synchronous iterations in each async iteration.
  9436. * @param fn the function to call each iteration.
  9437. * @param callback a success call back that will be called when iterating stops.
  9438. * @param breakFunction a break condition (optional)
  9439. * @param timeout timeout settings for the setTimeout function. default - 0.
  9440. * @constructor
  9441. */
  9442. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9443. if (timeout === void 0) { timeout = 0; }
  9444. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9445. if (breakFunction && breakFunction())
  9446. loop.breakLoop();
  9447. else {
  9448. setTimeout(function () {
  9449. for (var i = 0; i < syncedIterations; ++i) {
  9450. var iteration = (loop.index * syncedIterations) + i;
  9451. if (iteration >= iterations)
  9452. break;
  9453. fn(iteration);
  9454. if (breakFunction && breakFunction()) {
  9455. loop.breakLoop();
  9456. break;
  9457. }
  9458. }
  9459. loop.executeNext();
  9460. }, timeout);
  9461. }
  9462. }, callback);
  9463. };
  9464. return AsyncLoop;
  9465. }());
  9466. BABYLON.AsyncLoop = AsyncLoop;
  9467. })(BABYLON || (BABYLON = {}));
  9468. //# sourceMappingURL=babylon.tools.js.map
  9469. "use strict";
  9470. var BABYLON;
  9471. (function (BABYLON) {
  9472. var PromiseStates;
  9473. (function (PromiseStates) {
  9474. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9475. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9476. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9477. })(PromiseStates || (PromiseStates = {}));
  9478. var FulFillmentAgregator = /** @class */ (function () {
  9479. function FulFillmentAgregator() {
  9480. this.count = 0;
  9481. this.target = 0;
  9482. this.results = [];
  9483. }
  9484. return FulFillmentAgregator;
  9485. }());
  9486. var InternalPromise = /** @class */ (function () {
  9487. function InternalPromise(resolver) {
  9488. var _this = this;
  9489. this._state = PromiseStates.Pending;
  9490. this._children = new Array();
  9491. this._rejectWasConsumed = false;
  9492. if (!resolver) {
  9493. return;
  9494. }
  9495. try {
  9496. resolver(function (value) {
  9497. _this._resolve(value);
  9498. }, function (reason) {
  9499. _this._reject(reason);
  9500. });
  9501. }
  9502. catch (e) {
  9503. this._reject(e);
  9504. }
  9505. }
  9506. InternalPromise.prototype.catch = function (onRejected) {
  9507. return this.then(undefined, onRejected);
  9508. };
  9509. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9510. var _this = this;
  9511. var newPromise = new InternalPromise();
  9512. newPromise._onFulfilled = onFulfilled;
  9513. newPromise._onRejected = onRejected;
  9514. // Composition
  9515. this._children.push(newPromise);
  9516. if (this._state !== PromiseStates.Pending) {
  9517. BABYLON.Tools.SetImmediate(function () {
  9518. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9519. var returnedValue = newPromise._resolve(_this._result);
  9520. if (returnedValue !== undefined && returnedValue !== null) {
  9521. if (returnedValue._state !== undefined) {
  9522. var returnedPromise = returnedValue;
  9523. newPromise._children.push(returnedPromise);
  9524. newPromise = returnedPromise;
  9525. }
  9526. else {
  9527. newPromise._result = returnedValue;
  9528. }
  9529. }
  9530. }
  9531. else {
  9532. newPromise._reject(_this._reason);
  9533. }
  9534. });
  9535. }
  9536. return newPromise;
  9537. };
  9538. InternalPromise.prototype._moveChildren = function (children) {
  9539. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9540. if (this._state === PromiseStates.Fulfilled) {
  9541. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9542. var child = _b[_i];
  9543. child._resolve(this._result);
  9544. }
  9545. }
  9546. else if (this._state === PromiseStates.Rejected) {
  9547. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9548. var child = _d[_c];
  9549. child._reject(this._reason);
  9550. }
  9551. }
  9552. var _a;
  9553. };
  9554. InternalPromise.prototype._resolve = function (value) {
  9555. try {
  9556. this._state = PromiseStates.Fulfilled;
  9557. var returnedValue = null;
  9558. if (this._onFulfilled) {
  9559. returnedValue = this._onFulfilled(value);
  9560. }
  9561. if (returnedValue !== undefined && returnedValue !== null) {
  9562. if (returnedValue._state !== undefined) {
  9563. // Transmit children
  9564. var returnedPromise = returnedValue;
  9565. returnedPromise._moveChildren(this._children);
  9566. value = returnedPromise._result;
  9567. }
  9568. else {
  9569. value = returnedValue;
  9570. }
  9571. }
  9572. this._result = value;
  9573. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9574. var child = _a[_i];
  9575. child._resolve(value);
  9576. }
  9577. this._children.length = 0;
  9578. delete this._onFulfilled;
  9579. delete this._onRejected;
  9580. }
  9581. catch (e) {
  9582. this._reject(e, true);
  9583. }
  9584. };
  9585. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9586. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9587. this._state = PromiseStates.Rejected;
  9588. this._reason = reason;
  9589. if (this._onRejected && !onLocalThrow) {
  9590. try {
  9591. this._onRejected(reason);
  9592. this._rejectWasConsumed = true;
  9593. }
  9594. catch (e) {
  9595. reason = e;
  9596. }
  9597. }
  9598. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9599. var child = _a[_i];
  9600. if (this._rejectWasConsumed) {
  9601. child._resolve(null);
  9602. }
  9603. else {
  9604. child._reject(reason);
  9605. }
  9606. }
  9607. this._children.length = 0;
  9608. delete this._onFulfilled;
  9609. delete this._onRejected;
  9610. };
  9611. InternalPromise.resolve = function (value) {
  9612. var newPromise = new InternalPromise();
  9613. newPromise._resolve(value);
  9614. return newPromise;
  9615. };
  9616. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9617. promise.then(function (value) {
  9618. agregator.results[index] = value;
  9619. agregator.count++;
  9620. if (agregator.count === agregator.target) {
  9621. agregator.rootPromise._resolve(agregator.results);
  9622. }
  9623. return null;
  9624. }, function (reason) {
  9625. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9626. agregator.rootPromise._reject(reason);
  9627. }
  9628. });
  9629. };
  9630. InternalPromise.all = function (promises) {
  9631. var newPromise = new InternalPromise();
  9632. var agregator = new FulFillmentAgregator();
  9633. agregator.target = promises.length;
  9634. agregator.rootPromise = newPromise;
  9635. if (promises.length) {
  9636. for (var index = 0; index < promises.length; index++) {
  9637. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9638. }
  9639. }
  9640. else {
  9641. newPromise._resolve([]);
  9642. }
  9643. return newPromise;
  9644. };
  9645. InternalPromise.race = function (promises) {
  9646. var newPromise = new InternalPromise();
  9647. if (promises.length) {
  9648. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9649. var promise = promises_1[_i];
  9650. promise.then(function (value) {
  9651. if (newPromise) {
  9652. newPromise._resolve(value);
  9653. newPromise = null;
  9654. }
  9655. return null;
  9656. }, function (reason) {
  9657. if (newPromise) {
  9658. newPromise._reject(reason);
  9659. newPromise = null;
  9660. }
  9661. });
  9662. }
  9663. }
  9664. return newPromise;
  9665. };
  9666. return InternalPromise;
  9667. }());
  9668. /**
  9669. * Helper class that provides a small promise polyfill
  9670. */
  9671. var PromisePolyfill = /** @class */ (function () {
  9672. function PromisePolyfill() {
  9673. }
  9674. /**
  9675. * Static function used to check if the polyfill is required
  9676. * If this is the case then the function will inject the polyfill to window.Promise
  9677. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9678. */
  9679. PromisePolyfill.Apply = function (force) {
  9680. if (force === void 0) { force = false; }
  9681. if (force || typeof Promise === 'undefined') {
  9682. var root = window;
  9683. root.Promise = InternalPromise;
  9684. }
  9685. };
  9686. return PromisePolyfill;
  9687. }());
  9688. BABYLON.PromisePolyfill = PromisePolyfill;
  9689. })(BABYLON || (BABYLON = {}));
  9690. //# sourceMappingURL=babylon.promise.js.map
  9691. "use strict";
  9692. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9693. var BABYLON;
  9694. (function (BABYLON) {
  9695. /**
  9696. * Helper class to push actions to a pool of workers.
  9697. */
  9698. var WorkerPool = /** @class */ (function () {
  9699. /**
  9700. * Constructor
  9701. * @param workers Array of workers to use for actions
  9702. */
  9703. function WorkerPool(workers) {
  9704. this._pendingActions = new Array();
  9705. this._workerInfos = workers.map(function (worker) { return ({
  9706. worker: worker,
  9707. active: false
  9708. }); });
  9709. }
  9710. /**
  9711. * Terminates all workers and clears any pending actions.
  9712. */
  9713. WorkerPool.prototype.dispose = function () {
  9714. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9715. var workerInfo = _a[_i];
  9716. workerInfo.worker.terminate();
  9717. }
  9718. delete this._workerInfos;
  9719. delete this._pendingActions;
  9720. };
  9721. /**
  9722. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9723. * pended until a worker has completed its action.
  9724. * @param action The action to perform. Call onComplete when the action is complete.
  9725. */
  9726. WorkerPool.prototype.push = function (action) {
  9727. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9728. var workerInfo = _a[_i];
  9729. if (!workerInfo.active) {
  9730. this._execute(workerInfo, action);
  9731. return;
  9732. }
  9733. }
  9734. this._pendingActions.push(action);
  9735. };
  9736. WorkerPool.prototype._execute = function (workerInfo, action) {
  9737. var _this = this;
  9738. workerInfo.active = true;
  9739. action(workerInfo.worker, function () {
  9740. workerInfo.active = false;
  9741. var nextAction = _this._pendingActions.shift();
  9742. if (nextAction) {
  9743. _this._execute(workerInfo, nextAction);
  9744. }
  9745. });
  9746. };
  9747. return WorkerPool;
  9748. }());
  9749. BABYLON.WorkerPool = WorkerPool;
  9750. })(BABYLON || (BABYLON = {}));
  9751. //# sourceMappingURL=babylon.workerPool.js.map
  9752. "use strict";
  9753. var BABYLON;
  9754. (function (BABYLON) {
  9755. var _AlphaState = /** @class */ (function () {
  9756. /**
  9757. * Initializes the state.
  9758. */
  9759. function _AlphaState() {
  9760. this._isAlphaBlendDirty = false;
  9761. this._isBlendFunctionParametersDirty = false;
  9762. this._isBlendEquationParametersDirty = false;
  9763. this._isBlendConstantsDirty = false;
  9764. this._alphaBlend = false;
  9765. this._blendFunctionParameters = new Array(4);
  9766. this._blendEquationParameters = new Array(2);
  9767. this._blendConstants = new Array(4);
  9768. this.reset();
  9769. }
  9770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9771. get: function () {
  9772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9778. get: function () {
  9779. return this._alphaBlend;
  9780. },
  9781. set: function (value) {
  9782. if (this._alphaBlend === value) {
  9783. return;
  9784. }
  9785. this._alphaBlend = value;
  9786. this._isAlphaBlendDirty = true;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9792. if (this._blendConstants[0] === r &&
  9793. this._blendConstants[1] === g &&
  9794. this._blendConstants[2] === b &&
  9795. this._blendConstants[3] === a) {
  9796. return;
  9797. }
  9798. this._blendConstants[0] = r;
  9799. this._blendConstants[1] = g;
  9800. this._blendConstants[2] = b;
  9801. this._blendConstants[3] = a;
  9802. this._isBlendConstantsDirty = true;
  9803. };
  9804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9805. if (this._blendFunctionParameters[0] === value0 &&
  9806. this._blendFunctionParameters[1] === value1 &&
  9807. this._blendFunctionParameters[2] === value2 &&
  9808. this._blendFunctionParameters[3] === value3) {
  9809. return;
  9810. }
  9811. this._blendFunctionParameters[0] = value0;
  9812. this._blendFunctionParameters[1] = value1;
  9813. this._blendFunctionParameters[2] = value2;
  9814. this._blendFunctionParameters[3] = value3;
  9815. this._isBlendFunctionParametersDirty = true;
  9816. };
  9817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9818. if (this._blendEquationParameters[0] === rgb &&
  9819. this._blendEquationParameters[1] === alpha) {
  9820. return;
  9821. }
  9822. this._blendEquationParameters[0] = rgb;
  9823. this._blendEquationParameters[1] = alpha;
  9824. this._isBlendEquationParametersDirty = true;
  9825. };
  9826. _AlphaState.prototype.reset = function () {
  9827. this._alphaBlend = false;
  9828. this._blendFunctionParameters[0] = null;
  9829. this._blendFunctionParameters[1] = null;
  9830. this._blendFunctionParameters[2] = null;
  9831. this._blendFunctionParameters[3] = null;
  9832. this._blendEquationParameters[0] = null;
  9833. this._blendEquationParameters[1] = null;
  9834. this._blendConstants[0] = null;
  9835. this._blendConstants[1] = null;
  9836. this._blendConstants[2] = null;
  9837. this._blendConstants[3] = null;
  9838. this._isAlphaBlendDirty = true;
  9839. this._isBlendFunctionParametersDirty = false;
  9840. this._isBlendEquationParametersDirty = false;
  9841. this._isBlendConstantsDirty = false;
  9842. };
  9843. _AlphaState.prototype.apply = function (gl) {
  9844. if (!this.isDirty) {
  9845. return;
  9846. }
  9847. // Alpha blend
  9848. if (this._isAlphaBlendDirty) {
  9849. if (this._alphaBlend) {
  9850. gl.enable(gl.BLEND);
  9851. }
  9852. else {
  9853. gl.disable(gl.BLEND);
  9854. }
  9855. this._isAlphaBlendDirty = false;
  9856. }
  9857. // Alpha function
  9858. if (this._isBlendFunctionParametersDirty) {
  9859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9860. this._isBlendFunctionParametersDirty = false;
  9861. }
  9862. // Alpha equation
  9863. if (this._isBlendEquationParametersDirty) {
  9864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9865. this._isBlendEquationParametersDirty = false;
  9866. }
  9867. // Constants
  9868. if (this._isBlendConstantsDirty) {
  9869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9870. this._isBlendConstantsDirty = false;
  9871. }
  9872. };
  9873. return _AlphaState;
  9874. }());
  9875. BABYLON._AlphaState = _AlphaState;
  9876. })(BABYLON || (BABYLON = {}));
  9877. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9878. "use strict";
  9879. var BABYLON;
  9880. (function (BABYLON) {
  9881. var _DepthCullingState = /** @class */ (function () {
  9882. /**
  9883. * Initializes the state.
  9884. */
  9885. function _DepthCullingState() {
  9886. this._isDepthTestDirty = false;
  9887. this._isDepthMaskDirty = false;
  9888. this._isDepthFuncDirty = false;
  9889. this._isCullFaceDirty = false;
  9890. this._isCullDirty = false;
  9891. this._isZOffsetDirty = false;
  9892. this._isFrontFaceDirty = false;
  9893. this.reset();
  9894. }
  9895. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9896. get: function () {
  9897. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9898. },
  9899. enumerable: true,
  9900. configurable: true
  9901. });
  9902. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9903. get: function () {
  9904. return this._zOffset;
  9905. },
  9906. set: function (value) {
  9907. if (this._zOffset === value) {
  9908. return;
  9909. }
  9910. this._zOffset = value;
  9911. this._isZOffsetDirty = true;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9917. get: function () {
  9918. return this._cullFace;
  9919. },
  9920. set: function (value) {
  9921. if (this._cullFace === value) {
  9922. return;
  9923. }
  9924. this._cullFace = value;
  9925. this._isCullFaceDirty = true;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9931. get: function () {
  9932. return this._cull;
  9933. },
  9934. set: function (value) {
  9935. if (this._cull === value) {
  9936. return;
  9937. }
  9938. this._cull = value;
  9939. this._isCullDirty = true;
  9940. },
  9941. enumerable: true,
  9942. configurable: true
  9943. });
  9944. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9945. get: function () {
  9946. return this._depthFunc;
  9947. },
  9948. set: function (value) {
  9949. if (this._depthFunc === value) {
  9950. return;
  9951. }
  9952. this._depthFunc = value;
  9953. this._isDepthFuncDirty = true;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9959. get: function () {
  9960. return this._depthMask;
  9961. },
  9962. set: function (value) {
  9963. if (this._depthMask === value) {
  9964. return;
  9965. }
  9966. this._depthMask = value;
  9967. this._isDepthMaskDirty = true;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9973. get: function () {
  9974. return this._depthTest;
  9975. },
  9976. set: function (value) {
  9977. if (this._depthTest === value) {
  9978. return;
  9979. }
  9980. this._depthTest = value;
  9981. this._isDepthTestDirty = true;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9987. get: function () {
  9988. return this._frontFace;
  9989. },
  9990. set: function (value) {
  9991. if (this._frontFace === value) {
  9992. return;
  9993. }
  9994. this._frontFace = value;
  9995. this._isFrontFaceDirty = true;
  9996. },
  9997. enumerable: true,
  9998. configurable: true
  9999. });
  10000. _DepthCullingState.prototype.reset = function () {
  10001. this._depthMask = true;
  10002. this._depthTest = true;
  10003. this._depthFunc = null;
  10004. this._cullFace = null;
  10005. this._cull = null;
  10006. this._zOffset = 0;
  10007. this._frontFace = null;
  10008. this._isDepthTestDirty = true;
  10009. this._isDepthMaskDirty = true;
  10010. this._isDepthFuncDirty = false;
  10011. this._isCullFaceDirty = false;
  10012. this._isCullDirty = false;
  10013. this._isZOffsetDirty = false;
  10014. this._isFrontFaceDirty = false;
  10015. };
  10016. _DepthCullingState.prototype.apply = function (gl) {
  10017. if (!this.isDirty) {
  10018. return;
  10019. }
  10020. // Cull
  10021. if (this._isCullDirty) {
  10022. if (this.cull) {
  10023. gl.enable(gl.CULL_FACE);
  10024. }
  10025. else {
  10026. gl.disable(gl.CULL_FACE);
  10027. }
  10028. this._isCullDirty = false;
  10029. }
  10030. // Cull face
  10031. if (this._isCullFaceDirty) {
  10032. gl.cullFace(this.cullFace);
  10033. this._isCullFaceDirty = false;
  10034. }
  10035. // Depth mask
  10036. if (this._isDepthMaskDirty) {
  10037. gl.depthMask(this.depthMask);
  10038. this._isDepthMaskDirty = false;
  10039. }
  10040. // Depth test
  10041. if (this._isDepthTestDirty) {
  10042. if (this.depthTest) {
  10043. gl.enable(gl.DEPTH_TEST);
  10044. }
  10045. else {
  10046. gl.disable(gl.DEPTH_TEST);
  10047. }
  10048. this._isDepthTestDirty = false;
  10049. }
  10050. // Depth func
  10051. if (this._isDepthFuncDirty) {
  10052. gl.depthFunc(this.depthFunc);
  10053. this._isDepthFuncDirty = false;
  10054. }
  10055. // zOffset
  10056. if (this._isZOffsetDirty) {
  10057. if (this.zOffset) {
  10058. gl.enable(gl.POLYGON_OFFSET_FILL);
  10059. gl.polygonOffset(this.zOffset, 0);
  10060. }
  10061. else {
  10062. gl.disable(gl.POLYGON_OFFSET_FILL);
  10063. }
  10064. this._isZOffsetDirty = false;
  10065. }
  10066. // Front face
  10067. if (this._isFrontFaceDirty) {
  10068. gl.frontFace(this.frontFace);
  10069. this._isFrontFaceDirty = false;
  10070. }
  10071. };
  10072. return _DepthCullingState;
  10073. }());
  10074. BABYLON._DepthCullingState = _DepthCullingState;
  10075. })(BABYLON || (BABYLON = {}));
  10076. //# sourceMappingURL=babylon.depthCullingState.js.map
  10077. "use strict";
  10078. var BABYLON;
  10079. (function (BABYLON) {
  10080. var _StencilState = /** @class */ (function () {
  10081. function _StencilState() {
  10082. this._isStencilTestDirty = false;
  10083. this._isStencilMaskDirty = false;
  10084. this._isStencilFuncDirty = false;
  10085. this._isStencilOpDirty = false;
  10086. this.reset();
  10087. }
  10088. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10089. get: function () {
  10090. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10091. },
  10092. enumerable: true,
  10093. configurable: true
  10094. });
  10095. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10096. get: function () {
  10097. return this._stencilFunc;
  10098. },
  10099. set: function (value) {
  10100. if (this._stencilFunc === value) {
  10101. return;
  10102. }
  10103. this._stencilFunc = value;
  10104. this._isStencilFuncDirty = true;
  10105. },
  10106. enumerable: true,
  10107. configurable: true
  10108. });
  10109. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10110. get: function () {
  10111. return this._stencilFuncRef;
  10112. },
  10113. set: function (value) {
  10114. if (this._stencilFuncRef === value) {
  10115. return;
  10116. }
  10117. this._stencilFuncRef = value;
  10118. this._isStencilFuncDirty = true;
  10119. },
  10120. enumerable: true,
  10121. configurable: true
  10122. });
  10123. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10124. get: function () {
  10125. return this._stencilFuncMask;
  10126. },
  10127. set: function (value) {
  10128. if (this._stencilFuncMask === value) {
  10129. return;
  10130. }
  10131. this._stencilFuncMask = value;
  10132. this._isStencilFuncDirty = true;
  10133. },
  10134. enumerable: true,
  10135. configurable: true
  10136. });
  10137. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10138. get: function () {
  10139. return this._stencilOpStencilFail;
  10140. },
  10141. set: function (value) {
  10142. if (this._stencilOpStencilFail === value) {
  10143. return;
  10144. }
  10145. this._stencilOpStencilFail = value;
  10146. this._isStencilOpDirty = true;
  10147. },
  10148. enumerable: true,
  10149. configurable: true
  10150. });
  10151. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10152. get: function () {
  10153. return this._stencilOpDepthFail;
  10154. },
  10155. set: function (value) {
  10156. if (this._stencilOpDepthFail === value) {
  10157. return;
  10158. }
  10159. this._stencilOpDepthFail = value;
  10160. this._isStencilOpDirty = true;
  10161. },
  10162. enumerable: true,
  10163. configurable: true
  10164. });
  10165. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10166. get: function () {
  10167. return this._stencilOpStencilDepthPass;
  10168. },
  10169. set: function (value) {
  10170. if (this._stencilOpStencilDepthPass === value) {
  10171. return;
  10172. }
  10173. this._stencilOpStencilDepthPass = value;
  10174. this._isStencilOpDirty = true;
  10175. },
  10176. enumerable: true,
  10177. configurable: true
  10178. });
  10179. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10180. get: function () {
  10181. return this._stencilMask;
  10182. },
  10183. set: function (value) {
  10184. if (this._stencilMask === value) {
  10185. return;
  10186. }
  10187. this._stencilMask = value;
  10188. this._isStencilMaskDirty = true;
  10189. },
  10190. enumerable: true,
  10191. configurable: true
  10192. });
  10193. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10194. get: function () {
  10195. return this._stencilTest;
  10196. },
  10197. set: function (value) {
  10198. if (this._stencilTest === value) {
  10199. return;
  10200. }
  10201. this._stencilTest = value;
  10202. this._isStencilTestDirty = true;
  10203. },
  10204. enumerable: true,
  10205. configurable: true
  10206. });
  10207. _StencilState.prototype.reset = function () {
  10208. this._stencilTest = false;
  10209. this._stencilMask = 0xFF;
  10210. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10211. this._stencilFuncRef = 1;
  10212. this._stencilFuncMask = 0xFF;
  10213. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10214. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10215. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10216. this._isStencilTestDirty = true;
  10217. this._isStencilMaskDirty = true;
  10218. this._isStencilFuncDirty = true;
  10219. this._isStencilOpDirty = true;
  10220. };
  10221. _StencilState.prototype.apply = function (gl) {
  10222. if (!this.isDirty) {
  10223. return;
  10224. }
  10225. // Stencil test
  10226. if (this._isStencilTestDirty) {
  10227. if (this.stencilTest) {
  10228. gl.enable(gl.STENCIL_TEST);
  10229. }
  10230. else {
  10231. gl.disable(gl.STENCIL_TEST);
  10232. }
  10233. this._isStencilTestDirty = false;
  10234. }
  10235. // Stencil mask
  10236. if (this._isStencilMaskDirty) {
  10237. gl.stencilMask(this.stencilMask);
  10238. this._isStencilMaskDirty = false;
  10239. }
  10240. // Stencil func
  10241. if (this._isStencilFuncDirty) {
  10242. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10243. this._isStencilFuncDirty = false;
  10244. }
  10245. // Stencil op
  10246. if (this._isStencilOpDirty) {
  10247. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10248. this._isStencilOpDirty = false;
  10249. }
  10250. };
  10251. return _StencilState;
  10252. }());
  10253. BABYLON._StencilState = _StencilState;
  10254. })(BABYLON || (BABYLON = {}));
  10255. //# sourceMappingURL=babylon.stencilState.js.map
  10256. "use strict";
  10257. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10258. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10259. s = arguments[i];
  10260. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10261. t[p] = s[p];
  10262. }
  10263. return t;
  10264. };
  10265. var BABYLON;
  10266. (function (BABYLON) {
  10267. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10268. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10269. };
  10270. var compileRawShader = function (gl, source, type) {
  10271. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10272. gl.shaderSource(shader, source);
  10273. gl.compileShader(shader);
  10274. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10275. var log = gl.getShaderInfoLog(shader);
  10276. if (log) {
  10277. throw new Error(log);
  10278. }
  10279. }
  10280. if (!shader) {
  10281. throw new Error("Something went wrong while compile the shader.");
  10282. }
  10283. return shader;
  10284. };
  10285. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10286. var magFilter = gl.NEAREST;
  10287. var minFilter = gl.NEAREST;
  10288. switch (samplingMode) {
  10289. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10290. magFilter = gl.LINEAR;
  10291. if (generateMipMaps) {
  10292. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10293. }
  10294. else {
  10295. minFilter = gl.LINEAR;
  10296. }
  10297. break;
  10298. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10299. magFilter = gl.LINEAR;
  10300. if (generateMipMaps) {
  10301. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10302. }
  10303. else {
  10304. minFilter = gl.LINEAR;
  10305. }
  10306. break;
  10307. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10308. magFilter = gl.NEAREST;
  10309. if (generateMipMaps) {
  10310. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10311. }
  10312. else {
  10313. minFilter = gl.NEAREST;
  10314. }
  10315. break;
  10316. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10317. magFilter = gl.NEAREST;
  10318. if (generateMipMaps) {
  10319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10320. }
  10321. else {
  10322. minFilter = gl.NEAREST;
  10323. }
  10324. break;
  10325. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10326. magFilter = gl.NEAREST;
  10327. if (generateMipMaps) {
  10328. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10329. }
  10330. else {
  10331. minFilter = gl.LINEAR;
  10332. }
  10333. break;
  10334. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10335. magFilter = gl.NEAREST;
  10336. if (generateMipMaps) {
  10337. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10338. }
  10339. else {
  10340. minFilter = gl.LINEAR;
  10341. }
  10342. break;
  10343. case BABYLON.Texture.NEAREST_LINEAR:
  10344. magFilter = gl.NEAREST;
  10345. minFilter = gl.LINEAR;
  10346. break;
  10347. case BABYLON.Texture.NEAREST_NEAREST:
  10348. magFilter = gl.NEAREST;
  10349. minFilter = gl.NEAREST;
  10350. break;
  10351. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10352. magFilter = gl.LINEAR;
  10353. if (generateMipMaps) {
  10354. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10355. }
  10356. else {
  10357. minFilter = gl.NEAREST;
  10358. }
  10359. break;
  10360. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10361. magFilter = gl.LINEAR;
  10362. if (generateMipMaps) {
  10363. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10364. }
  10365. else {
  10366. minFilter = gl.NEAREST;
  10367. }
  10368. break;
  10369. case BABYLON.Texture.LINEAR_LINEAR:
  10370. magFilter = gl.LINEAR;
  10371. minFilter = gl.LINEAR;
  10372. break;
  10373. case BABYLON.Texture.LINEAR_NEAREST:
  10374. magFilter = gl.LINEAR;
  10375. minFilter = gl.NEAREST;
  10376. break;
  10377. }
  10378. return {
  10379. min: minFilter,
  10380. mag: magFilter
  10381. };
  10382. };
  10383. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10384. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10385. var img;
  10386. var onload = function () {
  10387. loadedImages[index] = img;
  10388. loadedImages._internalCount++;
  10389. if (scene) {
  10390. scene._removePendingData(img);
  10391. }
  10392. if (loadedImages._internalCount === 6) {
  10393. onfinish(loadedImages);
  10394. }
  10395. };
  10396. var onerror = function (message, exception) {
  10397. if (scene) {
  10398. scene._removePendingData(img);
  10399. }
  10400. if (onErrorCallBack) {
  10401. onErrorCallBack(message, exception);
  10402. }
  10403. };
  10404. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10405. if (scene) {
  10406. scene._addPendingData(img);
  10407. }
  10408. };
  10409. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10410. if (onError === void 0) { onError = null; }
  10411. var loadedImages = [];
  10412. loadedImages._internalCount = 0;
  10413. for (var index = 0; index < 6; index++) {
  10414. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10415. }
  10416. };
  10417. var BufferPointer = /** @class */ (function () {
  10418. function BufferPointer() {
  10419. }
  10420. return BufferPointer;
  10421. }());
  10422. var InstancingAttributeInfo = /** @class */ (function () {
  10423. function InstancingAttributeInfo() {
  10424. }
  10425. return InstancingAttributeInfo;
  10426. }());
  10427. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10428. /**
  10429. * Define options used to create a render target texture
  10430. */
  10431. var RenderTargetCreationOptions = /** @class */ (function () {
  10432. function RenderTargetCreationOptions() {
  10433. }
  10434. return RenderTargetCreationOptions;
  10435. }());
  10436. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10437. /**
  10438. * Define options used to create a depth texture
  10439. */
  10440. var DepthTextureCreationOptions = /** @class */ (function () {
  10441. function DepthTextureCreationOptions() {
  10442. }
  10443. return DepthTextureCreationOptions;
  10444. }());
  10445. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10446. /**
  10447. * Regroup several parameters relative to the browser in use
  10448. */
  10449. var EngineCapabilities = /** @class */ (function () {
  10450. function EngineCapabilities() {
  10451. }
  10452. return EngineCapabilities;
  10453. }());
  10454. BABYLON.EngineCapabilities = EngineCapabilities;
  10455. /**
  10456. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10457. */
  10458. var Engine = /** @class */ (function () {
  10459. /**
  10460. * @constructor
  10461. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10462. * @param antialias defines enable antialiasing (default: false)
  10463. * @param options defines further options to be sent to the getContext() function
  10464. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10465. */
  10466. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10467. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10468. var _this = this;
  10469. // Public members
  10470. this.forcePOTTextures = false;
  10471. this.isFullscreen = false;
  10472. this.isPointerLock = false;
  10473. this.cullBackFaces = true;
  10474. this.renderEvenInBackground = true;
  10475. this.preventCacheWipeBetweenFrames = false;
  10476. /**
  10477. * To enable/disable IDB support and avoid XHR on .manifest
  10478. **/
  10479. this.enableOfflineSupport = false;
  10480. this.scenes = new Array();
  10481. this.postProcesses = new Array();
  10482. // Observables
  10483. /**
  10484. * Observable event triggered each time the rendering canvas is resized
  10485. */
  10486. this.onResizeObservable = new BABYLON.Observable();
  10487. /**
  10488. * Observable event triggered each time the canvas loses focus
  10489. */
  10490. this.onCanvasBlurObservable = new BABYLON.Observable();
  10491. /**
  10492. * Observable event triggered each time the canvas gains focus
  10493. */
  10494. this.onCanvasFocusObservable = new BABYLON.Observable();
  10495. /**
  10496. * Observable event triggered each time the canvas receives pointerout event
  10497. */
  10498. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10499. /**
  10500. * Observable event triggered before each texture is initialized
  10501. */
  10502. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10503. //WebVR
  10504. this._vrDisplay = undefined;
  10505. this._vrSupported = false;
  10506. this._vrExclusivePointerMode = false;
  10507. // Uniform buffers list
  10508. this.disableUniformBuffers = false;
  10509. this._uniformBuffers = new Array();
  10510. // Observables
  10511. /**
  10512. * Observable raised when the engine begins a new frame
  10513. */
  10514. this.onBeginFrameObservable = new BABYLON.Observable();
  10515. /**
  10516. * Observable raised when the engine ends the current frame
  10517. */
  10518. this.onEndFrameObservable = new BABYLON.Observable();
  10519. /**
  10520. * Observable raised when the engine is about to compile a shader
  10521. */
  10522. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10523. /**
  10524. * Observable raised when the engine has jsut compiled a shader
  10525. */
  10526. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10527. this._windowIsBackground = false;
  10528. this._webGLVersion = 1.0;
  10529. this._badOS = false;
  10530. this._badDesktopOS = false;
  10531. /**
  10532. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10533. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10534. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10535. */
  10536. this.disableTextureBindingOptimization = false;
  10537. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10538. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10539. this.onVRRequestPresentStart = new BABYLON.Observable();
  10540. this._colorWrite = true;
  10541. this._drawCalls = new BABYLON.PerfCounter();
  10542. this._textureCollisions = new BABYLON.PerfCounter();
  10543. this._renderingQueueLaunched = false;
  10544. this._activeRenderLoops = new Array();
  10545. // Deterministic lockstepMaxSteps
  10546. this._deterministicLockstep = false;
  10547. this._lockstepMaxSteps = 4;
  10548. // Lost context
  10549. this.onContextLostObservable = new BABYLON.Observable();
  10550. this.onContextRestoredObservable = new BABYLON.Observable();
  10551. this._contextWasLost = false;
  10552. this._doNotHandleContextLost = false;
  10553. // FPS
  10554. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10555. this._fps = 60;
  10556. this._deltaTime = 0;
  10557. /**
  10558. * Turn this value on if you want to pause FPS computation when in background
  10559. */
  10560. this.disablePerformanceMonitorInBackground = false;
  10561. // States
  10562. this._depthCullingState = new BABYLON._DepthCullingState();
  10563. this._stencilState = new BABYLON._StencilState();
  10564. this._alphaState = new BABYLON._AlphaState();
  10565. this._alphaMode = Engine.ALPHA_DISABLE;
  10566. // Cache
  10567. this._internalTexturesCache = new Array();
  10568. this._activeChannel = 0;
  10569. this._currentTextureChannel = -1;
  10570. this._boundTexturesCache = {};
  10571. this._compiledEffects = {};
  10572. this._vertexAttribArraysEnabled = [];
  10573. this._uintIndicesCurrentlySet = false;
  10574. this._currentBoundBuffer = new Array();
  10575. this._currentBufferPointers = new Array();
  10576. this._currentInstanceLocations = new Array();
  10577. this._currentInstanceBuffers = new Array();
  10578. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10579. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10580. this._vaoRecordInProgress = false;
  10581. this._mustWipeVertexAttributes = false;
  10582. this._nextFreeTextureSlots = new Array();
  10583. this._maxSimultaneousTextures = 0;
  10584. this._activeRequests = new Array();
  10585. // Hardware supported Compressed Textures
  10586. this._texturesSupported = new Array();
  10587. this._onVRFullScreenTriggered = function () {
  10588. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10589. //get the old size before we change
  10590. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10591. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10592. //get the width and height, change the render size
  10593. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10594. _this.setHardwareScalingLevel(1);
  10595. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10596. }
  10597. else {
  10598. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10599. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10600. }
  10601. };
  10602. this._boundUniforms = {};
  10603. // Register promises
  10604. BABYLON.PromisePolyfill.Apply();
  10605. var canvas = null;
  10606. Engine.Instances.push(this);
  10607. if (!canvasOrContext) {
  10608. return;
  10609. }
  10610. options = options || {};
  10611. if (canvasOrContext.getContext) {
  10612. canvas = canvasOrContext;
  10613. this._renderingCanvas = canvas;
  10614. if (antialias != null) {
  10615. options.antialias = antialias;
  10616. }
  10617. if (options.deterministicLockstep === undefined) {
  10618. options.deterministicLockstep = false;
  10619. }
  10620. if (options.lockstepMaxSteps === undefined) {
  10621. options.lockstepMaxSteps = 4;
  10622. }
  10623. if (options.preserveDrawingBuffer === undefined) {
  10624. options.preserveDrawingBuffer = false;
  10625. }
  10626. if (options.audioEngine === undefined) {
  10627. options.audioEngine = true;
  10628. }
  10629. if (options.stencil === undefined) {
  10630. options.stencil = true;
  10631. }
  10632. this._deterministicLockstep = options.deterministicLockstep;
  10633. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10634. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10635. // Exceptions
  10636. if (navigator && navigator.userAgent) {
  10637. var ua = navigator.userAgent;
  10638. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10639. var exception = _a[_i];
  10640. var key = exception.key;
  10641. var targets = exception.targets;
  10642. if (ua.indexOf(key) > -1) {
  10643. if (exception.capture && exception.captureConstraint) {
  10644. var capture = exception.capture;
  10645. var constraint = exception.captureConstraint;
  10646. var regex = new RegExp(capture);
  10647. var matches = regex.exec(ua);
  10648. if (matches && matches.length > 0) {
  10649. var capturedValue = parseInt(matches[matches.length - 1]);
  10650. if (capturedValue >= constraint) {
  10651. continue;
  10652. }
  10653. }
  10654. }
  10655. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10656. var target = targets_1[_b];
  10657. switch (target) {
  10658. case "uniformBuffer":
  10659. this.disableUniformBuffers = true;
  10660. break;
  10661. case "textureBindingOptimization":
  10662. this.disableTextureBindingOptimization = true;
  10663. break;
  10664. }
  10665. }
  10666. }
  10667. }
  10668. }
  10669. // GL
  10670. if (!options.disableWebGL2Support) {
  10671. try {
  10672. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10673. if (this._gl) {
  10674. this._webGLVersion = 2.0;
  10675. }
  10676. }
  10677. catch (e) {
  10678. // Do nothing
  10679. }
  10680. }
  10681. if (!this._gl) {
  10682. if (!canvas) {
  10683. throw new Error("The provided canvas is null or undefined.");
  10684. }
  10685. try {
  10686. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10687. }
  10688. catch (e) {
  10689. throw new Error("WebGL not supported");
  10690. }
  10691. }
  10692. if (!this._gl) {
  10693. throw new Error("WebGL not supported");
  10694. }
  10695. this._onCanvasFocus = function () {
  10696. _this.onCanvasFocusObservable.notifyObservers(_this);
  10697. };
  10698. this._onCanvasBlur = function () {
  10699. _this.onCanvasBlurObservable.notifyObservers(_this);
  10700. };
  10701. canvas.addEventListener("focus", this._onCanvasFocus);
  10702. canvas.addEventListener("blur", this._onCanvasBlur);
  10703. this._onBlur = function () {
  10704. if (_this.disablePerformanceMonitorInBackground) {
  10705. _this._performanceMonitor.disable();
  10706. }
  10707. _this._windowIsBackground = true;
  10708. };
  10709. this._onFocus = function () {
  10710. if (_this.disablePerformanceMonitorInBackground) {
  10711. _this._performanceMonitor.enable();
  10712. }
  10713. _this._windowIsBackground = false;
  10714. };
  10715. this._onCanvasPointerOut = function (ev) {
  10716. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10717. };
  10718. window.addEventListener("blur", this._onBlur);
  10719. window.addEventListener("focus", this._onFocus);
  10720. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10721. // Context lost
  10722. if (!this._doNotHandleContextLost) {
  10723. this._onContextLost = function (evt) {
  10724. evt.preventDefault();
  10725. _this._contextWasLost = true;
  10726. BABYLON.Tools.Warn("WebGL context lost.");
  10727. _this.onContextLostObservable.notifyObservers(_this);
  10728. };
  10729. this._onContextRestored = function (evt) {
  10730. // Adding a timeout to avoid race condition at browser level
  10731. setTimeout(function () {
  10732. // Rebuild gl context
  10733. _this._initGLContext();
  10734. // Rebuild effects
  10735. _this._rebuildEffects();
  10736. // Rebuild textures
  10737. _this._rebuildInternalTextures();
  10738. // Rebuild buffers
  10739. _this._rebuildBuffers();
  10740. // Cache
  10741. _this.wipeCaches(true);
  10742. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10743. _this.onContextRestoredObservable.notifyObservers(_this);
  10744. _this._contextWasLost = false;
  10745. }, 0);
  10746. };
  10747. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10748. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10749. }
  10750. }
  10751. else {
  10752. this._gl = canvasOrContext;
  10753. this._renderingCanvas = this._gl.canvas;
  10754. if (this._gl.renderbufferStorageMultisample) {
  10755. this._webGLVersion = 2.0;
  10756. }
  10757. options.stencil = this._gl.getContextAttributes().stencil;
  10758. }
  10759. // Viewport
  10760. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10761. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10762. this.resize();
  10763. this._isStencilEnable = options.stencil ? true : false;
  10764. this._initGLContext();
  10765. if (canvas) {
  10766. // Fullscreen
  10767. this._onFullscreenChange = function () {
  10768. if (document.fullscreen !== undefined) {
  10769. _this.isFullscreen = document.fullscreen;
  10770. }
  10771. else if (document.mozFullScreen !== undefined) {
  10772. _this.isFullscreen = document.mozFullScreen;
  10773. }
  10774. else if (document.webkitIsFullScreen !== undefined) {
  10775. _this.isFullscreen = document.webkitIsFullScreen;
  10776. }
  10777. else if (document.msIsFullScreen !== undefined) {
  10778. _this.isFullscreen = document.msIsFullScreen;
  10779. }
  10780. // Pointer lock
  10781. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10782. canvas.requestPointerLock = canvas.requestPointerLock ||
  10783. canvas.msRequestPointerLock ||
  10784. canvas.mozRequestPointerLock ||
  10785. canvas.webkitRequestPointerLock;
  10786. if (canvas.requestPointerLock) {
  10787. canvas.requestPointerLock();
  10788. }
  10789. }
  10790. };
  10791. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10792. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10793. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10794. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10795. // Pointer lock
  10796. this._onPointerLockChange = function () {
  10797. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10798. document.webkitPointerLockElement === canvas ||
  10799. document.msPointerLockElement === canvas ||
  10800. document.pointerLockElement === canvas);
  10801. };
  10802. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10803. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10804. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10805. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10806. this._onVRDisplayPointerRestricted = function () {
  10807. if (canvas) {
  10808. canvas.requestPointerLock();
  10809. }
  10810. };
  10811. this._onVRDisplayPointerUnrestricted = function () {
  10812. document.exitPointerLock();
  10813. };
  10814. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10815. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10816. }
  10817. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10818. Engine.audioEngine = new BABYLON.AudioEngine();
  10819. }
  10820. // Prepare buffer pointers
  10821. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10822. this._currentBufferPointers[i] = new BufferPointer();
  10823. }
  10824. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10825. // Load WebVR Devices
  10826. if (options.autoEnableWebVR) {
  10827. this.initWebVR();
  10828. }
  10829. // Detect if we are running on a faulty buggy OS.
  10830. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10831. // Detect if we are running on a faulty buggy desktop OS.
  10832. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10833. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10834. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10835. }
  10836. Object.defineProperty(Engine, "LastCreatedEngine", {
  10837. get: function () {
  10838. if (Engine.Instances.length === 0) {
  10839. return null;
  10840. }
  10841. return Engine.Instances[Engine.Instances.length - 1];
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine, "LastCreatedScene", {
  10847. get: function () {
  10848. var lastCreatedEngine = Engine.LastCreatedEngine;
  10849. if (!lastCreatedEngine) {
  10850. return null;
  10851. }
  10852. if (lastCreatedEngine.scenes.length === 0) {
  10853. return null;
  10854. }
  10855. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. /**
  10861. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10862. */
  10863. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10864. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10865. var engine = Engine.Instances[engineIndex];
  10866. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10867. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10868. }
  10869. }
  10870. };
  10871. Object.defineProperty(Engine, "NEVER", {
  10872. get: function () {
  10873. return Engine._NEVER;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine, "ALWAYS", {
  10879. get: function () {
  10880. return Engine._ALWAYS;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine, "LESS", {
  10886. get: function () {
  10887. return Engine._LESS;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine, "EQUAL", {
  10893. get: function () {
  10894. return Engine._EQUAL;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "LEQUAL", {
  10900. get: function () {
  10901. return Engine._LEQUAL;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine, "GREATER", {
  10907. get: function () {
  10908. return Engine._GREATER;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "GEQUAL", {
  10914. get: function () {
  10915. return Engine._GEQUAL;
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine, "NOTEQUAL", {
  10921. get: function () {
  10922. return Engine._NOTEQUAL;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine, "KEEP", {
  10928. get: function () {
  10929. return Engine._KEEP;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine, "REPLACE", {
  10935. get: function () {
  10936. return Engine._REPLACE;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine, "INCR", {
  10942. get: function () {
  10943. return Engine._INCR;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine, "DECR", {
  10949. get: function () {
  10950. return Engine._DECR;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine, "INVERT", {
  10956. get: function () {
  10957. return Engine._INVERT;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine, "INCR_WRAP", {
  10963. get: function () {
  10964. return Engine._INCR_WRAP;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine, "DECR_WRAP", {
  10970. get: function () {
  10971. return Engine._DECR_WRAP;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10977. get: function () {
  10978. return Engine._ALPHA_DISABLE;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10984. get: function () {
  10985. return Engine._ALPHA_ONEONE;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine, "ALPHA_ADD", {
  10991. get: function () {
  10992. return Engine._ALPHA_ADD;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10998. get: function () {
  10999. return Engine._ALPHA_COMBINE;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11005. get: function () {
  11006. return Engine._ALPHA_SUBTRACT;
  11007. },
  11008. enumerable: true,
  11009. configurable: true
  11010. });
  11011. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11012. get: function () {
  11013. return Engine._ALPHA_MULTIPLY;
  11014. },
  11015. enumerable: true,
  11016. configurable: true
  11017. });
  11018. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11019. get: function () {
  11020. return Engine._ALPHA_MAXIMIZED;
  11021. },
  11022. enumerable: true,
  11023. configurable: true
  11024. });
  11025. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11026. get: function () {
  11027. return Engine._ALPHA_PREMULTIPLIED;
  11028. },
  11029. enumerable: true,
  11030. configurable: true
  11031. });
  11032. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11033. get: function () {
  11034. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11035. },
  11036. enumerable: true,
  11037. configurable: true
  11038. });
  11039. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11040. get: function () {
  11041. return Engine._ALPHA_INTERPOLATE;
  11042. },
  11043. enumerable: true,
  11044. configurable: true
  11045. });
  11046. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11047. get: function () {
  11048. return Engine._ALPHA_SCREENMODE;
  11049. },
  11050. enumerable: true,
  11051. configurable: true
  11052. });
  11053. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11054. get: function () {
  11055. return Engine._DELAYLOADSTATE_NONE;
  11056. },
  11057. enumerable: true,
  11058. configurable: true
  11059. });
  11060. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11061. get: function () {
  11062. return Engine._DELAYLOADSTATE_LOADED;
  11063. },
  11064. enumerable: true,
  11065. configurable: true
  11066. });
  11067. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11068. get: function () {
  11069. return Engine._DELAYLOADSTATE_LOADING;
  11070. },
  11071. enumerable: true,
  11072. configurable: true
  11073. });
  11074. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11075. get: function () {
  11076. return Engine._DELAYLOADSTATE_NOTLOADED;
  11077. },
  11078. enumerable: true,
  11079. configurable: true
  11080. });
  11081. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11082. get: function () {
  11083. return Engine._TEXTUREFORMAT_ALPHA;
  11084. },
  11085. enumerable: true,
  11086. configurable: true
  11087. });
  11088. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11089. get: function () {
  11090. return Engine._TEXTUREFORMAT_LUMINANCE;
  11091. },
  11092. enumerable: true,
  11093. configurable: true
  11094. });
  11095. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11096. /**
  11097. * R32F
  11098. */
  11099. get: function () {
  11100. return Engine._TEXTUREFORMAT_R32F;
  11101. },
  11102. enumerable: true,
  11103. configurable: true
  11104. });
  11105. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11106. /**
  11107. * RG32F
  11108. */
  11109. get: function () {
  11110. return Engine._TEXTUREFORMAT_RG32F;
  11111. },
  11112. enumerable: true,
  11113. configurable: true
  11114. });
  11115. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11116. /**
  11117. * RGB32F
  11118. */
  11119. get: function () {
  11120. return Engine._TEXTUREFORMAT_RGB32F;
  11121. },
  11122. enumerable: true,
  11123. configurable: true
  11124. });
  11125. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11126. /**
  11127. * RGBA32F
  11128. */
  11129. get: function () {
  11130. return Engine._TEXTUREFORMAT_RGBA32F;
  11131. },
  11132. enumerable: true,
  11133. configurable: true
  11134. });
  11135. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11136. get: function () {
  11137. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11138. },
  11139. enumerable: true,
  11140. configurable: true
  11141. });
  11142. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11143. get: function () {
  11144. return Engine._TEXTUREFORMAT_RGB;
  11145. },
  11146. enumerable: true,
  11147. configurable: true
  11148. });
  11149. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11150. get: function () {
  11151. return Engine._TEXTUREFORMAT_RGBA;
  11152. },
  11153. enumerable: true,
  11154. configurable: true
  11155. });
  11156. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11157. get: function () {
  11158. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11159. },
  11160. enumerable: true,
  11161. configurable: true
  11162. });
  11163. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11164. get: function () {
  11165. return Engine._TEXTURETYPE_FLOAT;
  11166. },
  11167. enumerable: true,
  11168. configurable: true
  11169. });
  11170. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11171. get: function () {
  11172. return Engine._TEXTURETYPE_HALF_FLOAT;
  11173. },
  11174. enumerable: true,
  11175. configurable: true
  11176. });
  11177. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11178. get: function () {
  11179. return Engine._SCALEMODE_FLOOR;
  11180. },
  11181. enumerable: true,
  11182. configurable: true
  11183. });
  11184. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11185. get: function () {
  11186. return Engine._SCALEMODE_NEAREST;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11192. get: function () {
  11193. return Engine._SCALEMODE_CEILING;
  11194. },
  11195. enumerable: true,
  11196. configurable: true
  11197. });
  11198. Object.defineProperty(Engine, "Version", {
  11199. get: function () {
  11200. return "3.2.0-beta.3";
  11201. },
  11202. enumerable: true,
  11203. configurable: true
  11204. });
  11205. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11206. get: function () {
  11207. return this._vrExclusivePointerMode;
  11208. },
  11209. enumerable: true,
  11210. configurable: true
  11211. });
  11212. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11213. get: function () {
  11214. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11215. },
  11216. enumerable: true,
  11217. configurable: true
  11218. });
  11219. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11220. get: function () {
  11221. return this._webGLVersion < 2 || this.forcePOTTextures;
  11222. },
  11223. enumerable: true,
  11224. configurable: true
  11225. });
  11226. Object.defineProperty(Engine.prototype, "badOS", {
  11227. get: function () {
  11228. return this._badOS;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11234. get: function () {
  11235. return this._badDesktopOS;
  11236. },
  11237. enumerable: true,
  11238. configurable: true
  11239. });
  11240. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11241. get: function () {
  11242. return this._performanceMonitor;
  11243. },
  11244. enumerable: true,
  11245. configurable: true
  11246. });
  11247. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11248. get: function () {
  11249. return this._texturesSupported;
  11250. },
  11251. enumerable: true,
  11252. configurable: true
  11253. });
  11254. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11255. get: function () {
  11256. return this._textureFormatInUse;
  11257. },
  11258. enumerable: true,
  11259. configurable: true
  11260. });
  11261. Object.defineProperty(Engine.prototype, "currentViewport", {
  11262. get: function () {
  11263. return this._cachedViewport;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11269. // Empty texture
  11270. get: function () {
  11271. if (!this._emptyTexture) {
  11272. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11273. }
  11274. return this._emptyTexture;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11280. get: function () {
  11281. if (!this._emptyTexture3D) {
  11282. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11283. }
  11284. return this._emptyTexture3D;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11290. get: function () {
  11291. if (!this._emptyCubeTexture) {
  11292. var faceData = new Uint8Array(4);
  11293. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11294. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11295. }
  11296. return this._emptyCubeTexture;
  11297. },
  11298. enumerable: true,
  11299. configurable: true
  11300. });
  11301. Engine.prototype._rebuildInternalTextures = function () {
  11302. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11303. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11304. var internalTexture = currentState_1[_i];
  11305. internalTexture._rebuild();
  11306. }
  11307. };
  11308. Engine.prototype._rebuildEffects = function () {
  11309. for (var key in this._compiledEffects) {
  11310. var effect = this._compiledEffects[key];
  11311. effect._prepareEffect();
  11312. }
  11313. BABYLON.Effect.ResetCache();
  11314. };
  11315. Engine.prototype._rebuildBuffers = function () {
  11316. // Index / Vertex
  11317. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11318. var scene = _a[_i];
  11319. scene.resetCachedMaterial();
  11320. scene._rebuildGeometries();
  11321. scene._rebuildTextures();
  11322. }
  11323. // Uniforms
  11324. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11325. var uniformBuffer = _c[_b];
  11326. uniformBuffer._rebuild();
  11327. }
  11328. };
  11329. Engine.prototype._initGLContext = function () {
  11330. // Caps
  11331. this._caps = new EngineCapabilities();
  11332. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11333. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11334. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11335. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11336. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11337. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11338. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11339. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11340. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11341. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11342. // Infos
  11343. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11344. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11345. if (rendererInfo != null) {
  11346. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11347. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11348. }
  11349. if (!this._glVendor) {
  11350. this._glVendor = "Unknown vendor";
  11351. }
  11352. if (!this._glRenderer) {
  11353. this._glRenderer = "Unknown renderer";
  11354. }
  11355. // Constants
  11356. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11357. if (this._gl.RGBA16F !== 0x881A) {
  11358. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11359. }
  11360. if (this._gl.RGBA32F !== 0x8814) {
  11361. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11362. }
  11363. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11364. this._gl.DEPTH24_STENCIL8 = 35056;
  11365. }
  11366. // Extensions
  11367. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11368. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11369. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11370. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11371. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11372. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11373. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11374. 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');
  11375. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11376. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11377. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11378. this._caps.highPrecisionShaderSupported = true;
  11379. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11380. if (this._caps.timerQuery) {
  11381. if (this._webGLVersion === 1) {
  11382. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11383. }
  11384. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11385. }
  11386. // Checks if some of the format renders first to allow the use of webgl inspector.
  11387. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11388. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11389. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11390. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11391. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11392. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11393. if (this._webGLVersion > 1) {
  11394. this._gl.HALF_FLOAT_OES = 0x140B;
  11395. }
  11396. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11397. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11398. // Draw buffers
  11399. if (this._webGLVersion > 1) {
  11400. this._caps.drawBuffersExtension = true;
  11401. }
  11402. else {
  11403. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11404. if (drawBuffersExtension !== null) {
  11405. this._caps.drawBuffersExtension = true;
  11406. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11407. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11408. for (var i = 0; i < 16; i++) {
  11409. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11410. }
  11411. }
  11412. else {
  11413. this._caps.drawBuffersExtension = false;
  11414. }
  11415. }
  11416. // Depth Texture
  11417. if (this._webGLVersion > 1) {
  11418. this._caps.depthTextureExtension = true;
  11419. }
  11420. else {
  11421. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11422. if (depthTextureExtension != null) {
  11423. this._caps.depthTextureExtension = true;
  11424. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11425. }
  11426. }
  11427. // Vertex array object
  11428. if (this._webGLVersion > 1) {
  11429. this._caps.vertexArrayObject = true;
  11430. }
  11431. else {
  11432. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11433. if (vertexArrayObjectExtension != null) {
  11434. this._caps.vertexArrayObject = true;
  11435. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11436. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11437. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11438. }
  11439. else {
  11440. this._caps.vertexArrayObject = false;
  11441. }
  11442. }
  11443. // Instances count
  11444. if (this._webGLVersion > 1) {
  11445. this._caps.instancedArrays = true;
  11446. }
  11447. else {
  11448. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11449. if (instanceExtension != null) {
  11450. this._caps.instancedArrays = true;
  11451. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11452. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11453. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11454. }
  11455. else {
  11456. this._caps.instancedArrays = false;
  11457. }
  11458. }
  11459. // Intelligently add supported compressed formats in order to check for.
  11460. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11461. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11462. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11463. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11464. if (this._caps.astc)
  11465. this.texturesSupported.push('-astc.ktx');
  11466. if (this._caps.s3tc)
  11467. this.texturesSupported.push('-dxt.ktx');
  11468. if (this._caps.pvrtc)
  11469. this.texturesSupported.push('-pvrtc.ktx');
  11470. if (this._caps.etc2)
  11471. this.texturesSupported.push('-etc2.ktx');
  11472. if (this._caps.etc1)
  11473. this.texturesSupported.push('-etc1.ktx');
  11474. if (this._gl.getShaderPrecisionFormat) {
  11475. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11476. if (highp) {
  11477. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11478. }
  11479. }
  11480. // Depth buffer
  11481. this.setDepthBuffer(true);
  11482. this.setDepthFunctionToLessOrEqual();
  11483. this.setDepthWrite(true);
  11484. // Texture maps
  11485. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11486. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11487. this._nextFreeTextureSlots.push(slot);
  11488. }
  11489. };
  11490. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11491. get: function () {
  11492. return this._webGLVersion;
  11493. },
  11494. enumerable: true,
  11495. configurable: true
  11496. });
  11497. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11498. /**
  11499. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11500. */
  11501. get: function () {
  11502. return this._isStencilEnable;
  11503. },
  11504. enumerable: true,
  11505. configurable: true
  11506. });
  11507. Engine.prototype._prepareWorkingCanvas = function () {
  11508. if (this._workingCanvas) {
  11509. return;
  11510. }
  11511. this._workingCanvas = document.createElement("canvas");
  11512. var context = this._workingCanvas.getContext("2d");
  11513. if (context) {
  11514. this._workingContext = context;
  11515. }
  11516. };
  11517. Engine.prototype.resetTextureCache = function () {
  11518. for (var key in this._boundTexturesCache) {
  11519. var boundTexture = this._boundTexturesCache[key];
  11520. if (boundTexture) {
  11521. this._removeDesignatedSlot(boundTexture);
  11522. }
  11523. this._boundTexturesCache[key] = null;
  11524. }
  11525. if (!this.disableTextureBindingOptimization) {
  11526. this._nextFreeTextureSlots = [];
  11527. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11528. this._nextFreeTextureSlots.push(slot);
  11529. }
  11530. }
  11531. this._currentTextureChannel = -1;
  11532. };
  11533. Engine.prototype.isDeterministicLockStep = function () {
  11534. return this._deterministicLockstep;
  11535. };
  11536. Engine.prototype.getLockstepMaxSteps = function () {
  11537. return this._lockstepMaxSteps;
  11538. };
  11539. Engine.prototype.getGlInfo = function () {
  11540. return {
  11541. vendor: this._glVendor,
  11542. renderer: this._glRenderer,
  11543. version: this._glVersion
  11544. };
  11545. };
  11546. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11547. if (useScreen === void 0) { useScreen = false; }
  11548. var viewport = camera.viewport;
  11549. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11550. };
  11551. Engine.prototype.getRenderWidth = function (useScreen) {
  11552. if (useScreen === void 0) { useScreen = false; }
  11553. if (!useScreen && this._currentRenderTarget) {
  11554. return this._currentRenderTarget.width;
  11555. }
  11556. return this._gl.drawingBufferWidth;
  11557. };
  11558. Engine.prototype.getRenderHeight = function (useScreen) {
  11559. if (useScreen === void 0) { useScreen = false; }
  11560. if (!useScreen && this._currentRenderTarget) {
  11561. return this._currentRenderTarget.height;
  11562. }
  11563. return this._gl.drawingBufferHeight;
  11564. };
  11565. Engine.prototype.getRenderingCanvas = function () {
  11566. return this._renderingCanvas;
  11567. };
  11568. Engine.prototype.getRenderingCanvasClientRect = function () {
  11569. if (!this._renderingCanvas) {
  11570. return null;
  11571. }
  11572. return this._renderingCanvas.getBoundingClientRect();
  11573. };
  11574. Engine.prototype.setHardwareScalingLevel = function (level) {
  11575. this._hardwareScalingLevel = level;
  11576. this.resize();
  11577. };
  11578. Engine.prototype.getHardwareScalingLevel = function () {
  11579. return this._hardwareScalingLevel;
  11580. };
  11581. Engine.prototype.getLoadedTexturesCache = function () {
  11582. return this._internalTexturesCache;
  11583. };
  11584. Engine.prototype.getCaps = function () {
  11585. return this._caps;
  11586. };
  11587. Object.defineProperty(Engine.prototype, "drawCalls", {
  11588. /** The number of draw calls submitted last frame */
  11589. get: function () {
  11590. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11591. return 0;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11597. get: function () {
  11598. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11599. return null;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Engine.prototype.getDepthFunction = function () {
  11605. return this._depthCullingState.depthFunc;
  11606. };
  11607. Engine.prototype.setDepthFunction = function (depthFunc) {
  11608. this._depthCullingState.depthFunc = depthFunc;
  11609. };
  11610. Engine.prototype.setDepthFunctionToGreater = function () {
  11611. this._depthCullingState.depthFunc = this._gl.GREATER;
  11612. };
  11613. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11614. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11615. };
  11616. Engine.prototype.setDepthFunctionToLess = function () {
  11617. this._depthCullingState.depthFunc = this._gl.LESS;
  11618. };
  11619. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11620. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11621. };
  11622. Engine.prototype.getStencilBuffer = function () {
  11623. return this._stencilState.stencilTest;
  11624. };
  11625. Engine.prototype.setStencilBuffer = function (enable) {
  11626. this._stencilState.stencilTest = enable;
  11627. };
  11628. Engine.prototype.getStencilMask = function () {
  11629. return this._stencilState.stencilMask;
  11630. };
  11631. Engine.prototype.setStencilMask = function (mask) {
  11632. this._stencilState.stencilMask = mask;
  11633. };
  11634. Engine.prototype.getStencilFunction = function () {
  11635. return this._stencilState.stencilFunc;
  11636. };
  11637. Engine.prototype.getStencilFunctionReference = function () {
  11638. return this._stencilState.stencilFuncRef;
  11639. };
  11640. Engine.prototype.getStencilFunctionMask = function () {
  11641. return this._stencilState.stencilFuncMask;
  11642. };
  11643. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11644. this._stencilState.stencilFunc = stencilFunc;
  11645. };
  11646. Engine.prototype.setStencilFunctionReference = function (reference) {
  11647. this._stencilState.stencilFuncRef = reference;
  11648. };
  11649. Engine.prototype.setStencilFunctionMask = function (mask) {
  11650. this._stencilState.stencilFuncMask = mask;
  11651. };
  11652. Engine.prototype.getStencilOperationFail = function () {
  11653. return this._stencilState.stencilOpStencilFail;
  11654. };
  11655. Engine.prototype.getStencilOperationDepthFail = function () {
  11656. return this._stencilState.stencilOpDepthFail;
  11657. };
  11658. Engine.prototype.getStencilOperationPass = function () {
  11659. return this._stencilState.stencilOpStencilDepthPass;
  11660. };
  11661. Engine.prototype.setStencilOperationFail = function (operation) {
  11662. this._stencilState.stencilOpStencilFail = operation;
  11663. };
  11664. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11665. this._stencilState.stencilOpDepthFail = operation;
  11666. };
  11667. Engine.prototype.setStencilOperationPass = function (operation) {
  11668. this._stencilState.stencilOpStencilDepthPass = operation;
  11669. };
  11670. Engine.prototype.setDitheringState = function (value) {
  11671. if (value) {
  11672. this._gl.enable(this._gl.DITHER);
  11673. }
  11674. else {
  11675. this._gl.disable(this._gl.DITHER);
  11676. }
  11677. };
  11678. Engine.prototype.setRasterizerState = function (value) {
  11679. if (value) {
  11680. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11681. }
  11682. else {
  11683. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11684. }
  11685. };
  11686. /**
  11687. * stop executing a render loop function and remove it from the execution array
  11688. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11689. */
  11690. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11691. if (!renderFunction) {
  11692. this._activeRenderLoops = [];
  11693. return;
  11694. }
  11695. var index = this._activeRenderLoops.indexOf(renderFunction);
  11696. if (index >= 0) {
  11697. this._activeRenderLoops.splice(index, 1);
  11698. }
  11699. };
  11700. Engine.prototype._renderLoop = function () {
  11701. if (!this._contextWasLost) {
  11702. var shouldRender = true;
  11703. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11704. shouldRender = false;
  11705. }
  11706. if (shouldRender) {
  11707. // Start new frame
  11708. this.beginFrame();
  11709. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11710. var renderFunction = this._activeRenderLoops[index];
  11711. renderFunction();
  11712. }
  11713. // Present
  11714. this.endFrame();
  11715. }
  11716. }
  11717. if (this._activeRenderLoops.length > 0) {
  11718. // Register new frame
  11719. var requester = null;
  11720. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11721. requester = this._vrDisplay;
  11722. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11723. }
  11724. else {
  11725. this._renderingQueueLaunched = false;
  11726. }
  11727. };
  11728. /**
  11729. * Register and execute a render loop. The engine can have more than one render function.
  11730. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11731. * @example
  11732. * engine.runRenderLoop(function () {
  11733. * scene.render()
  11734. * })
  11735. */
  11736. Engine.prototype.runRenderLoop = function (renderFunction) {
  11737. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11738. return;
  11739. }
  11740. this._activeRenderLoops.push(renderFunction);
  11741. if (!this._renderingQueueLaunched) {
  11742. this._renderingQueueLaunched = true;
  11743. this._bindedRenderFunction = this._renderLoop.bind(this);
  11744. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11745. }
  11746. };
  11747. /**
  11748. * Toggle full screen mode.
  11749. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11750. * @param {any} options - an options object to be sent to the requestFullscreen function
  11751. */
  11752. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11753. if (this.isFullscreen) {
  11754. BABYLON.Tools.ExitFullscreen();
  11755. }
  11756. else {
  11757. this._pointerLockRequested = requestPointerLock;
  11758. if (this._renderingCanvas) {
  11759. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11760. }
  11761. }
  11762. };
  11763. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11764. if (stencil === void 0) { stencil = false; }
  11765. this.applyStates();
  11766. var mode = 0;
  11767. if (backBuffer && color) {
  11768. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11769. mode |= this._gl.COLOR_BUFFER_BIT;
  11770. }
  11771. if (depth) {
  11772. this._gl.clearDepth(1.0);
  11773. mode |= this._gl.DEPTH_BUFFER_BIT;
  11774. }
  11775. if (stencil) {
  11776. this._gl.clearStencil(0);
  11777. mode |= this._gl.STENCIL_BUFFER_BIT;
  11778. }
  11779. this._gl.clear(mode);
  11780. };
  11781. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11782. var gl = this._gl;
  11783. // Save state
  11784. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11785. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11786. // Change state
  11787. gl.enable(gl.SCISSOR_TEST);
  11788. gl.scissor(x, y, width, height);
  11789. // Clear
  11790. this.clear(clearColor, true, true, true);
  11791. // Restore state
  11792. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11793. if (curScissor === true) {
  11794. gl.enable(gl.SCISSOR_TEST);
  11795. }
  11796. else {
  11797. gl.disable(gl.SCISSOR_TEST);
  11798. }
  11799. };
  11800. /**
  11801. * Set the WebGL's viewport
  11802. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11803. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11804. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11805. */
  11806. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11807. var width = requiredWidth || this.getRenderWidth();
  11808. var height = requiredHeight || this.getRenderHeight();
  11809. var x = viewport.x || 0;
  11810. var y = viewport.y || 0;
  11811. this._cachedViewport = viewport;
  11812. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11813. };
  11814. /**
  11815. * Directly set the WebGL Viewport
  11816. * The x, y, width & height are directly passed to the WebGL call
  11817. * @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.
  11818. */
  11819. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11820. var currentViewport = this._cachedViewport;
  11821. this._cachedViewport = null;
  11822. this._gl.viewport(x, y, width, height);
  11823. return currentViewport;
  11824. };
  11825. Engine.prototype.beginFrame = function () {
  11826. this.onBeginFrameObservable.notifyObservers(this);
  11827. this._measureFps();
  11828. };
  11829. Engine.prototype.endFrame = function () {
  11830. //force a flush in case we are using a bad OS.
  11831. if (this._badOS) {
  11832. this.flushFramebuffer();
  11833. }
  11834. //submit frame to the vr device, if enabled
  11835. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11836. // TODO: We should only submit the frame if we read frameData successfully.
  11837. this._vrDisplay.submitFrame();
  11838. }
  11839. this.onEndFrameObservable.notifyObservers(this);
  11840. };
  11841. /**
  11842. * resize the view according to the canvas' size.
  11843. * @example
  11844. * window.addEventListener("resize", function () {
  11845. * engine.resize();
  11846. * });
  11847. */
  11848. Engine.prototype.resize = function () {
  11849. // We're not resizing the size of the canvas while in VR mode & presenting
  11850. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11851. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11852. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11853. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11854. }
  11855. };
  11856. /**
  11857. * force a specific size of the canvas
  11858. * @param {number} width - the new canvas' width
  11859. * @param {number} height - the new canvas' height
  11860. */
  11861. Engine.prototype.setSize = function (width, height) {
  11862. if (!this._renderingCanvas) {
  11863. return;
  11864. }
  11865. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11866. return;
  11867. }
  11868. this._renderingCanvas.width = width;
  11869. this._renderingCanvas.height = height;
  11870. for (var index = 0; index < this.scenes.length; index++) {
  11871. var scene = this.scenes[index];
  11872. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11873. var cam = scene.cameras[camIndex];
  11874. cam._currentRenderId = 0;
  11875. }
  11876. }
  11877. if (this.onResizeObservable.hasObservers) {
  11878. this.onResizeObservable.notifyObservers(this);
  11879. }
  11880. };
  11881. // WebVR functions
  11882. Engine.prototype.isVRDevicePresent = function () {
  11883. return !!this._vrDisplay;
  11884. };
  11885. Engine.prototype.getVRDevice = function () {
  11886. return this._vrDisplay;
  11887. };
  11888. /**
  11889. * Initializes a webVR display and starts listening to display change events.
  11890. * The onVRDisplayChangedObservable will be notified upon these changes.
  11891. * @returns The onVRDisplayChangedObservable.
  11892. */
  11893. Engine.prototype.initWebVR = function () {
  11894. this.initWebVRAsync();
  11895. return this.onVRDisplayChangedObservable;
  11896. };
  11897. /**
  11898. * Initializes a webVR display and starts listening to display change events.
  11899. * The onVRDisplayChangedObservable will be notified upon these changes.
  11900. * @returns A promise containing a VRDisplay and if vr is supported.
  11901. */
  11902. Engine.prototype.initWebVRAsync = function () {
  11903. var _this = this;
  11904. var notifyObservers = function () {
  11905. var eventArgs = {
  11906. vrDisplay: _this._vrDisplay,
  11907. vrSupported: _this._vrSupported
  11908. };
  11909. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11910. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11911. };
  11912. if (!this._onVrDisplayConnect) {
  11913. this._onVrDisplayConnect = function (event) {
  11914. _this._vrDisplay = event.display;
  11915. notifyObservers();
  11916. };
  11917. this._onVrDisplayDisconnect = function () {
  11918. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11919. _this._vrDisplay = undefined;
  11920. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11921. notifyObservers();
  11922. };
  11923. this._onVrDisplayPresentChange = function () {
  11924. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11925. };
  11926. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11927. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11928. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11929. }
  11930. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11931. this._webVRInitPromise.then(notifyObservers);
  11932. return this._webVRInitPromise;
  11933. };
  11934. Engine.prototype.enableVR = function () {
  11935. var _this = this;
  11936. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11937. var onResolved = function () {
  11938. _this.onVRRequestPresentComplete.notifyObservers(true);
  11939. _this._onVRFullScreenTriggered();
  11940. };
  11941. var onRejected = function () {
  11942. _this.onVRRequestPresentComplete.notifyObservers(false);
  11943. };
  11944. this.onVRRequestPresentStart.notifyObservers(this);
  11945. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11946. }
  11947. };
  11948. Engine.prototype.disableVR = function () {
  11949. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11950. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11951. }
  11952. };
  11953. Engine.prototype._getVRDisplaysAsync = function () {
  11954. var _this = this;
  11955. return new Promise(function (res, rej) {
  11956. if (navigator.getVRDisplays) {
  11957. navigator.getVRDisplays().then(function (devices) {
  11958. _this._vrSupported = true;
  11959. // note that devices may actually be an empty array. This is fine;
  11960. // we expect this._vrDisplay to be undefined in this case.
  11961. _this._vrDisplay = devices[0];
  11962. res({
  11963. vrDisplay: _this._vrDisplay,
  11964. vrSupported: _this._vrSupported
  11965. });
  11966. });
  11967. }
  11968. else {
  11969. _this._vrDisplay = undefined;
  11970. _this._vrSupported = false;
  11971. res({
  11972. vrDisplay: _this._vrDisplay,
  11973. vrSupported: _this._vrSupported
  11974. });
  11975. }
  11976. });
  11977. };
  11978. /**
  11979. * Binds the frame buffer to the specified texture.
  11980. * @param texture The texture to render to or null for the default canvas
  11981. * @param faceIndex The face of the texture to render to in case of cube texture
  11982. * @param requiredWidth The width of the target to render to
  11983. * @param requiredHeight The height of the target to render to
  11984. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11985. * @param depthStencilTexture The depth stencil texture to use to render
  11986. */
  11987. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11988. if (this._currentRenderTarget) {
  11989. this.unBindFramebuffer(this._currentRenderTarget);
  11990. }
  11991. this._currentRenderTarget = texture;
  11992. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11993. var gl = this._gl;
  11994. if (texture.isCube) {
  11995. if (faceIndex === undefined) {
  11996. faceIndex = 0;
  11997. }
  11998. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11999. if (depthStencilTexture) {
  12000. if (depthStencilTexture._generateStencilBuffer) {
  12001. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12002. }
  12003. else {
  12004. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12005. }
  12006. }
  12007. }
  12008. if (this._cachedViewport && !forceFullscreenViewport) {
  12009. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12010. }
  12011. else {
  12012. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12013. }
  12014. this.wipeCaches();
  12015. };
  12016. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12017. if (this._currentFramebuffer !== framebuffer) {
  12018. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12019. this._currentFramebuffer = framebuffer;
  12020. }
  12021. };
  12022. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12023. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12024. this._currentRenderTarget = null;
  12025. // If MSAA, we need to bitblt back to main texture
  12026. var gl = this._gl;
  12027. if (texture._MSAAFramebuffer) {
  12028. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12029. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12030. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12031. }
  12032. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12033. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12034. gl.generateMipmap(gl.TEXTURE_2D);
  12035. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12036. }
  12037. if (onBeforeUnbind) {
  12038. if (texture._MSAAFramebuffer) {
  12039. // Bind the correct framebuffer
  12040. this.bindUnboundFramebuffer(texture._framebuffer);
  12041. }
  12042. onBeforeUnbind();
  12043. }
  12044. this.bindUnboundFramebuffer(null);
  12045. };
  12046. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12047. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12048. this._currentRenderTarget = null;
  12049. // If MSAA, we need to bitblt back to main texture
  12050. var gl = this._gl;
  12051. if (textures[0]._MSAAFramebuffer) {
  12052. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12053. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12054. var attachments = textures[0]._attachments;
  12055. if (!attachments) {
  12056. attachments = new Array(textures.length);
  12057. textures[0]._attachments = attachments;
  12058. }
  12059. for (var i = 0; i < textures.length; i++) {
  12060. var texture = textures[i];
  12061. for (var j = 0; j < attachments.length; j++) {
  12062. attachments[j] = gl.NONE;
  12063. }
  12064. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12065. gl.readBuffer(attachments[i]);
  12066. gl.drawBuffers(attachments);
  12067. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12068. }
  12069. for (var i = 0; i < attachments.length; i++) {
  12070. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12071. }
  12072. gl.drawBuffers(attachments);
  12073. }
  12074. for (var i = 0; i < textures.length; i++) {
  12075. var texture = textures[i];
  12076. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12077. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12078. gl.generateMipmap(gl.TEXTURE_2D);
  12079. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12080. }
  12081. }
  12082. if (onBeforeUnbind) {
  12083. if (textures[0]._MSAAFramebuffer) {
  12084. // Bind the correct framebuffer
  12085. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12086. }
  12087. onBeforeUnbind();
  12088. }
  12089. this.bindUnboundFramebuffer(null);
  12090. };
  12091. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12092. if (texture.generateMipMaps) {
  12093. var gl = this._gl;
  12094. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12095. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12097. }
  12098. };
  12099. Engine.prototype.flushFramebuffer = function () {
  12100. this._gl.flush();
  12101. };
  12102. Engine.prototype.restoreDefaultFramebuffer = function () {
  12103. if (this._currentRenderTarget) {
  12104. this.unBindFramebuffer(this._currentRenderTarget);
  12105. }
  12106. else {
  12107. this.bindUnboundFramebuffer(null);
  12108. }
  12109. if (this._cachedViewport) {
  12110. this.setViewport(this._cachedViewport);
  12111. }
  12112. this.wipeCaches();
  12113. };
  12114. // UBOs
  12115. Engine.prototype.createUniformBuffer = function (elements) {
  12116. var ubo = this._gl.createBuffer();
  12117. if (!ubo) {
  12118. throw new Error("Unable to create uniform buffer");
  12119. }
  12120. this.bindUniformBuffer(ubo);
  12121. if (elements instanceof Float32Array) {
  12122. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12123. }
  12124. else {
  12125. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12126. }
  12127. this.bindUniformBuffer(null);
  12128. ubo.references = 1;
  12129. return ubo;
  12130. };
  12131. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12132. var ubo = this._gl.createBuffer();
  12133. if (!ubo) {
  12134. throw new Error("Unable to create dynamic uniform buffer");
  12135. }
  12136. this.bindUniformBuffer(ubo);
  12137. if (elements instanceof Float32Array) {
  12138. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12139. }
  12140. else {
  12141. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12142. }
  12143. this.bindUniformBuffer(null);
  12144. ubo.references = 1;
  12145. return ubo;
  12146. };
  12147. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12148. this.bindUniformBuffer(uniformBuffer);
  12149. if (offset === undefined) {
  12150. offset = 0;
  12151. }
  12152. if (count === undefined) {
  12153. if (elements instanceof Float32Array) {
  12154. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12155. }
  12156. else {
  12157. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12158. }
  12159. }
  12160. else {
  12161. if (elements instanceof Float32Array) {
  12162. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12163. }
  12164. else {
  12165. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12166. }
  12167. }
  12168. this.bindUniformBuffer(null);
  12169. };
  12170. // VBOs
  12171. Engine.prototype._resetVertexBufferBinding = function () {
  12172. this.bindArrayBuffer(null);
  12173. this._cachedVertexBuffers = null;
  12174. };
  12175. Engine.prototype.createVertexBuffer = function (vertices) {
  12176. var vbo = this._gl.createBuffer();
  12177. if (!vbo) {
  12178. throw new Error("Unable to create vertex buffer");
  12179. }
  12180. this.bindArrayBuffer(vbo);
  12181. if (vertices instanceof Float32Array) {
  12182. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12183. }
  12184. else {
  12185. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12186. }
  12187. this._resetVertexBufferBinding();
  12188. vbo.references = 1;
  12189. return vbo;
  12190. };
  12191. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12192. var vbo = this._gl.createBuffer();
  12193. if (!vbo) {
  12194. throw new Error("Unable to create dynamic vertex buffer");
  12195. }
  12196. this.bindArrayBuffer(vbo);
  12197. if (vertices instanceof Float32Array) {
  12198. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12199. }
  12200. else {
  12201. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12202. }
  12203. this._resetVertexBufferBinding();
  12204. vbo.references = 1;
  12205. return vbo;
  12206. };
  12207. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12208. if (offset === void 0) { offset = 0; }
  12209. // Force cache update
  12210. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12211. this.bindIndexBuffer(indexBuffer);
  12212. var arrayBuffer;
  12213. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12214. arrayBuffer = indices;
  12215. }
  12216. else {
  12217. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12218. }
  12219. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12220. this._resetIndexBufferBinding();
  12221. };
  12222. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12223. this.bindArrayBuffer(vertexBuffer);
  12224. if (offset === undefined) {
  12225. offset = 0;
  12226. }
  12227. if (count === undefined) {
  12228. if (vertices instanceof Float32Array) {
  12229. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12230. }
  12231. else {
  12232. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12233. }
  12234. }
  12235. else {
  12236. if (vertices instanceof Float32Array) {
  12237. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12238. }
  12239. else {
  12240. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12241. }
  12242. }
  12243. this._resetVertexBufferBinding();
  12244. };
  12245. Engine.prototype._resetIndexBufferBinding = function () {
  12246. this.bindIndexBuffer(null);
  12247. this._cachedIndexBuffer = null;
  12248. };
  12249. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12250. var vbo = this._gl.createBuffer();
  12251. if (!vbo) {
  12252. throw new Error("Unable to create index buffer");
  12253. }
  12254. this.bindIndexBuffer(vbo);
  12255. // Check for 32 bits indices
  12256. var arrayBuffer;
  12257. var need32Bits = false;
  12258. if (indices instanceof Uint16Array) {
  12259. arrayBuffer = indices;
  12260. }
  12261. else {
  12262. //check 32 bit support
  12263. if (this._caps.uintIndices) {
  12264. if (indices instanceof Uint32Array) {
  12265. arrayBuffer = indices;
  12266. need32Bits = true;
  12267. }
  12268. else {
  12269. //number[] or Int32Array, check if 32 bit is necessary
  12270. for (var index = 0; index < indices.length; index++) {
  12271. if (indices[index] > 65535) {
  12272. need32Bits = true;
  12273. break;
  12274. }
  12275. }
  12276. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12277. }
  12278. }
  12279. else {
  12280. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12281. arrayBuffer = new Uint16Array(indices);
  12282. }
  12283. }
  12284. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12285. this._resetIndexBufferBinding();
  12286. vbo.references = 1;
  12287. vbo.is32Bits = need32Bits;
  12288. return vbo;
  12289. };
  12290. Engine.prototype.bindArrayBuffer = function (buffer) {
  12291. if (!this._vaoRecordInProgress) {
  12292. this._unbindVertexArrayObject();
  12293. }
  12294. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12295. };
  12296. Engine.prototype.bindUniformBuffer = function (buffer) {
  12297. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12298. };
  12299. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12300. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12301. };
  12302. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12303. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12304. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12305. };
  12306. ;
  12307. Engine.prototype.bindIndexBuffer = function (buffer) {
  12308. if (!this._vaoRecordInProgress) {
  12309. this._unbindVertexArrayObject();
  12310. }
  12311. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12312. };
  12313. Engine.prototype.bindBuffer = function (buffer, target) {
  12314. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12315. this._gl.bindBuffer(target, buffer);
  12316. this._currentBoundBuffer[target] = buffer;
  12317. }
  12318. };
  12319. Engine.prototype.updateArrayBuffer = function (data) {
  12320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12321. };
  12322. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12323. var pointer = this._currentBufferPointers[indx];
  12324. var changed = false;
  12325. if (!pointer.active) {
  12326. changed = true;
  12327. pointer.active = true;
  12328. pointer.index = indx;
  12329. pointer.size = size;
  12330. pointer.type = type;
  12331. pointer.normalized = normalized;
  12332. pointer.stride = stride;
  12333. pointer.offset = offset;
  12334. pointer.buffer = buffer;
  12335. }
  12336. else {
  12337. if (pointer.buffer !== buffer) {
  12338. pointer.buffer = buffer;
  12339. changed = true;
  12340. }
  12341. if (pointer.size !== size) {
  12342. pointer.size = size;
  12343. changed = true;
  12344. }
  12345. if (pointer.type !== type) {
  12346. pointer.type = type;
  12347. changed = true;
  12348. }
  12349. if (pointer.normalized !== normalized) {
  12350. pointer.normalized = normalized;
  12351. changed = true;
  12352. }
  12353. if (pointer.stride !== stride) {
  12354. pointer.stride = stride;
  12355. changed = true;
  12356. }
  12357. if (pointer.offset !== offset) {
  12358. pointer.offset = offset;
  12359. changed = true;
  12360. }
  12361. }
  12362. if (changed || this._vaoRecordInProgress) {
  12363. this.bindArrayBuffer(buffer);
  12364. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12365. }
  12366. };
  12367. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12368. if (indexBuffer == null) {
  12369. return;
  12370. }
  12371. if (this._cachedIndexBuffer !== indexBuffer) {
  12372. this._cachedIndexBuffer = indexBuffer;
  12373. this.bindIndexBuffer(indexBuffer);
  12374. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12375. }
  12376. };
  12377. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12378. var attributes = effect.getAttributesNames();
  12379. if (!this._vaoRecordInProgress) {
  12380. this._unbindVertexArrayObject();
  12381. }
  12382. this.unbindAllAttributes();
  12383. for (var index = 0; index < attributes.length; index++) {
  12384. var order = effect.getAttributeLocation(index);
  12385. if (order >= 0) {
  12386. var vertexBuffer = vertexBuffers[attributes[index]];
  12387. if (!vertexBuffer) {
  12388. continue;
  12389. }
  12390. this._gl.enableVertexAttribArray(order);
  12391. if (!this._vaoRecordInProgress) {
  12392. this._vertexAttribArraysEnabled[order] = true;
  12393. }
  12394. var buffer = vertexBuffer.getBuffer();
  12395. if (buffer) {
  12396. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12397. if (vertexBuffer.getIsInstanced()) {
  12398. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12399. if (!this._vaoRecordInProgress) {
  12400. this._currentInstanceLocations.push(order);
  12401. this._currentInstanceBuffers.push(buffer);
  12402. }
  12403. }
  12404. }
  12405. }
  12406. }
  12407. };
  12408. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12409. var vao = this._gl.createVertexArray();
  12410. this._vaoRecordInProgress = true;
  12411. this._gl.bindVertexArray(vao);
  12412. this._mustWipeVertexAttributes = true;
  12413. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12414. this.bindIndexBuffer(indexBuffer);
  12415. this._vaoRecordInProgress = false;
  12416. this._gl.bindVertexArray(null);
  12417. return vao;
  12418. };
  12419. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12420. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12421. this._cachedVertexArrayObject = vertexArrayObject;
  12422. this._gl.bindVertexArray(vertexArrayObject);
  12423. this._cachedVertexBuffers = null;
  12424. this._cachedIndexBuffer = null;
  12425. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12426. this._mustWipeVertexAttributes = true;
  12427. }
  12428. };
  12429. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12430. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12431. this._cachedVertexBuffers = vertexBuffer;
  12432. this._cachedEffectForVertexBuffers = effect;
  12433. var attributesCount = effect.getAttributesCount();
  12434. this._unbindVertexArrayObject();
  12435. this.unbindAllAttributes();
  12436. var offset = 0;
  12437. for (var index = 0; index < attributesCount; index++) {
  12438. if (index < vertexDeclaration.length) {
  12439. var order = effect.getAttributeLocation(index);
  12440. if (order >= 0) {
  12441. this._gl.enableVertexAttribArray(order);
  12442. this._vertexAttribArraysEnabled[order] = true;
  12443. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12444. }
  12445. offset += vertexDeclaration[index] * 4;
  12446. }
  12447. }
  12448. }
  12449. this._bindIndexBufferWithCache(indexBuffer);
  12450. };
  12451. Engine.prototype._unbindVertexArrayObject = function () {
  12452. if (!this._cachedVertexArrayObject) {
  12453. return;
  12454. }
  12455. this._cachedVertexArrayObject = null;
  12456. this._gl.bindVertexArray(null);
  12457. };
  12458. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12459. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12460. this._cachedVertexBuffers = vertexBuffers;
  12461. this._cachedEffectForVertexBuffers = effect;
  12462. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12463. }
  12464. this._bindIndexBufferWithCache(indexBuffer);
  12465. };
  12466. Engine.prototype.unbindInstanceAttributes = function () {
  12467. var boundBuffer;
  12468. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12469. var instancesBuffer = this._currentInstanceBuffers[i];
  12470. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12471. boundBuffer = instancesBuffer;
  12472. this.bindArrayBuffer(instancesBuffer);
  12473. }
  12474. var offsetLocation = this._currentInstanceLocations[i];
  12475. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12476. }
  12477. this._currentInstanceBuffers.length = 0;
  12478. this._currentInstanceLocations.length = 0;
  12479. };
  12480. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12481. this._gl.deleteVertexArray(vao);
  12482. };
  12483. Engine.prototype._releaseBuffer = function (buffer) {
  12484. buffer.references--;
  12485. if (buffer.references === 0) {
  12486. this._gl.deleteBuffer(buffer);
  12487. return true;
  12488. }
  12489. return false;
  12490. };
  12491. Engine.prototype.createInstancesBuffer = function (capacity) {
  12492. var buffer = this._gl.createBuffer();
  12493. if (!buffer) {
  12494. throw new Error("Unable to create instance buffer");
  12495. }
  12496. buffer.capacity = capacity;
  12497. this.bindArrayBuffer(buffer);
  12498. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12499. return buffer;
  12500. };
  12501. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12502. this._gl.deleteBuffer(buffer);
  12503. };
  12504. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12505. this.bindArrayBuffer(instancesBuffer);
  12506. if (data) {
  12507. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12508. }
  12509. if (offsetLocations[0].index !== undefined) {
  12510. var stride = 0;
  12511. for (var i = 0; i < offsetLocations.length; i++) {
  12512. var ai = offsetLocations[i];
  12513. stride += ai.attributeSize * 4;
  12514. }
  12515. for (var i = 0; i < offsetLocations.length; i++) {
  12516. var ai = offsetLocations[i];
  12517. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12518. this._gl.enableVertexAttribArray(ai.index);
  12519. this._vertexAttribArraysEnabled[ai.index] = true;
  12520. }
  12521. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12522. this._gl.vertexAttribDivisor(ai.index, 1);
  12523. this._currentInstanceLocations.push(ai.index);
  12524. this._currentInstanceBuffers.push(instancesBuffer);
  12525. }
  12526. }
  12527. else {
  12528. for (var index = 0; index < 4; index++) {
  12529. var offsetLocation = offsetLocations[index];
  12530. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12531. this._gl.enableVertexAttribArray(offsetLocation);
  12532. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12533. }
  12534. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12535. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12536. this._currentInstanceLocations.push(offsetLocation);
  12537. this._currentInstanceBuffers.push(instancesBuffer);
  12538. }
  12539. }
  12540. };
  12541. Engine.prototype.applyStates = function () {
  12542. this._depthCullingState.apply(this._gl);
  12543. this._stencilState.apply(this._gl);
  12544. this._alphaState.apply(this._gl);
  12545. };
  12546. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12547. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12548. };
  12549. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12550. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12551. };
  12552. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12553. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12554. };
  12555. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12556. // Apply states
  12557. this.applyStates();
  12558. this._drawCalls.addCount(1, false);
  12559. // Render
  12560. var drawMode = this._drawMode(fillMode);
  12561. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12562. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12563. if (instancesCount) {
  12564. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12565. }
  12566. else {
  12567. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12568. }
  12569. };
  12570. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12571. // Apply states
  12572. this.applyStates();
  12573. this._drawCalls.addCount(1, false);
  12574. var drawMode = this._drawMode(fillMode);
  12575. if (instancesCount) {
  12576. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12577. }
  12578. else {
  12579. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12580. }
  12581. };
  12582. Engine.prototype._drawMode = function (fillMode) {
  12583. switch (fillMode) {
  12584. // Triangle views
  12585. case BABYLON.Material.TriangleFillMode:
  12586. return this._gl.TRIANGLES;
  12587. case BABYLON.Material.PointFillMode:
  12588. return this._gl.POINTS;
  12589. case BABYLON.Material.WireFrameFillMode:
  12590. return this._gl.LINES;
  12591. // Draw modes
  12592. case BABYLON.Material.PointListDrawMode:
  12593. return this._gl.POINTS;
  12594. case BABYLON.Material.LineListDrawMode:
  12595. return this._gl.LINES;
  12596. case BABYLON.Material.LineLoopDrawMode:
  12597. return this._gl.LINE_LOOP;
  12598. case BABYLON.Material.LineStripDrawMode:
  12599. return this._gl.LINE_STRIP;
  12600. case BABYLON.Material.TriangleStripDrawMode:
  12601. return this._gl.TRIANGLE_STRIP;
  12602. case BABYLON.Material.TriangleFanDrawMode:
  12603. return this._gl.TRIANGLE_FAN;
  12604. default:
  12605. return this._gl.TRIANGLES;
  12606. }
  12607. };
  12608. // Shaders
  12609. Engine.prototype._releaseEffect = function (effect) {
  12610. if (this._compiledEffects[effect._key]) {
  12611. delete this._compiledEffects[effect._key];
  12612. this._deleteProgram(effect.getProgram());
  12613. }
  12614. };
  12615. Engine.prototype._deleteProgram = function (program) {
  12616. if (program) {
  12617. program.__SPECTOR_rebuildProgram = null;
  12618. if (program.transformFeedback) {
  12619. this.deleteTransformFeedback(program.transformFeedback);
  12620. program.transformFeedback = null;
  12621. }
  12622. this._gl.deleteProgram(program);
  12623. }
  12624. };
  12625. /**
  12626. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12627. * @param samplers An array of string used to represent textures
  12628. */
  12629. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12630. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12631. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12632. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12633. if (this._compiledEffects[name]) {
  12634. var compiledEffect = this._compiledEffects[name];
  12635. if (onCompiled && compiledEffect.isReady()) {
  12636. onCompiled(compiledEffect);
  12637. }
  12638. return compiledEffect;
  12639. }
  12640. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12641. effect._key = name;
  12642. this._compiledEffects[name] = effect;
  12643. return effect;
  12644. };
  12645. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12646. if (uniformsNames === void 0) { uniformsNames = []; }
  12647. if (samplers === void 0) { samplers = []; }
  12648. if (defines === void 0) { defines = ""; }
  12649. return this.createEffect({
  12650. vertex: "particles",
  12651. fragmentElement: fragmentName
  12652. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12653. };
  12654. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12655. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12656. context = context || this._gl;
  12657. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12658. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12659. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12660. };
  12661. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12662. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12663. context = context || this._gl;
  12664. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12665. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12666. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12667. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12668. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12669. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12670. return program;
  12671. };
  12672. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12673. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12674. var shaderProgram = context.createProgram();
  12675. if (!shaderProgram) {
  12676. throw new Error("Unable to create program");
  12677. }
  12678. context.attachShader(shaderProgram, vertexShader);
  12679. context.attachShader(shaderProgram, fragmentShader);
  12680. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12681. var transformFeedback = this.createTransformFeedback();
  12682. this.bindTransformFeedback(transformFeedback);
  12683. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12684. shaderProgram.transformFeedback = transformFeedback;
  12685. }
  12686. context.linkProgram(shaderProgram);
  12687. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12688. this.bindTransformFeedback(null);
  12689. }
  12690. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12691. if (!linked) {
  12692. context.validateProgram(shaderProgram);
  12693. var error = context.getProgramInfoLog(shaderProgram);
  12694. if (error) {
  12695. throw new Error(error);
  12696. }
  12697. }
  12698. context.deleteShader(vertexShader);
  12699. context.deleteShader(fragmentShader);
  12700. return shaderProgram;
  12701. };
  12702. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12703. var results = new Array();
  12704. for (var index = 0; index < uniformsNames.length; index++) {
  12705. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12706. }
  12707. return results;
  12708. };
  12709. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12710. var results = [];
  12711. for (var index = 0; index < attributesNames.length; index++) {
  12712. try {
  12713. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12714. }
  12715. catch (e) {
  12716. results.push(-1);
  12717. }
  12718. }
  12719. return results;
  12720. };
  12721. Engine.prototype.enableEffect = function (effect) {
  12722. if (!effect) {
  12723. return;
  12724. }
  12725. // Use program
  12726. this.bindSamplers(effect);
  12727. this._currentEffect = effect;
  12728. if (effect.onBind) {
  12729. effect.onBind(effect);
  12730. }
  12731. effect.onBindObservable.notifyObservers(effect);
  12732. };
  12733. Engine.prototype.setIntArray = function (uniform, array) {
  12734. if (!uniform)
  12735. return;
  12736. this._gl.uniform1iv(uniform, array);
  12737. };
  12738. Engine.prototype.setIntArray2 = function (uniform, array) {
  12739. if (!uniform || array.length % 2 !== 0)
  12740. return;
  12741. this._gl.uniform2iv(uniform, array);
  12742. };
  12743. Engine.prototype.setIntArray3 = function (uniform, array) {
  12744. if (!uniform || array.length % 3 !== 0)
  12745. return;
  12746. this._gl.uniform3iv(uniform, array);
  12747. };
  12748. Engine.prototype.setIntArray4 = function (uniform, array) {
  12749. if (!uniform || array.length % 4 !== 0)
  12750. return;
  12751. this._gl.uniform4iv(uniform, array);
  12752. };
  12753. Engine.prototype.setFloatArray = function (uniform, array) {
  12754. if (!uniform)
  12755. return;
  12756. this._gl.uniform1fv(uniform, array);
  12757. };
  12758. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12759. if (!uniform || array.length % 2 !== 0)
  12760. return;
  12761. this._gl.uniform2fv(uniform, array);
  12762. };
  12763. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12764. if (!uniform || array.length % 3 !== 0)
  12765. return;
  12766. this._gl.uniform3fv(uniform, array);
  12767. };
  12768. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12769. if (!uniform || array.length % 4 !== 0)
  12770. return;
  12771. this._gl.uniform4fv(uniform, array);
  12772. };
  12773. Engine.prototype.setArray = function (uniform, array) {
  12774. if (!uniform)
  12775. return;
  12776. this._gl.uniform1fv(uniform, array);
  12777. };
  12778. Engine.prototype.setArray2 = function (uniform, array) {
  12779. if (!uniform || array.length % 2 !== 0)
  12780. return;
  12781. this._gl.uniform2fv(uniform, array);
  12782. };
  12783. Engine.prototype.setArray3 = function (uniform, array) {
  12784. if (!uniform || array.length % 3 !== 0)
  12785. return;
  12786. this._gl.uniform3fv(uniform, array);
  12787. };
  12788. Engine.prototype.setArray4 = function (uniform, array) {
  12789. if (!uniform || array.length % 4 !== 0)
  12790. return;
  12791. this._gl.uniform4fv(uniform, array);
  12792. };
  12793. Engine.prototype.setMatrices = function (uniform, matrices) {
  12794. if (!uniform)
  12795. return;
  12796. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12797. };
  12798. Engine.prototype.setMatrix = function (uniform, matrix) {
  12799. if (!uniform)
  12800. return;
  12801. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12802. };
  12803. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12804. if (!uniform)
  12805. return;
  12806. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12807. };
  12808. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12809. if (!uniform)
  12810. return;
  12811. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12812. };
  12813. Engine.prototype.setInt = function (uniform, value) {
  12814. if (!uniform)
  12815. return;
  12816. this._gl.uniform1i(uniform, value);
  12817. };
  12818. Engine.prototype.setFloat = function (uniform, value) {
  12819. if (!uniform)
  12820. return;
  12821. this._gl.uniform1f(uniform, value);
  12822. };
  12823. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12824. if (!uniform)
  12825. return;
  12826. this._gl.uniform2f(uniform, x, y);
  12827. };
  12828. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12829. if (!uniform)
  12830. return;
  12831. this._gl.uniform3f(uniform, x, y, z);
  12832. };
  12833. Engine.prototype.setBool = function (uniform, bool) {
  12834. if (!uniform)
  12835. return;
  12836. this._gl.uniform1i(uniform, bool);
  12837. };
  12838. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12839. if (!uniform)
  12840. return;
  12841. this._gl.uniform4f(uniform, x, y, z, w);
  12842. };
  12843. Engine.prototype.setColor3 = function (uniform, color3) {
  12844. if (!uniform)
  12845. return;
  12846. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12847. };
  12848. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12849. if (!uniform)
  12850. return;
  12851. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12852. };
  12853. /**
  12854. * Sets a Color4 on a uniform variable
  12855. * @param uniform defines the uniform location
  12856. * @param color4 defines the value to be set
  12857. */
  12858. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12859. if (!uniform)
  12860. return;
  12861. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12862. };
  12863. // States
  12864. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12865. if (zOffset === void 0) { zOffset = 0; }
  12866. if (reverseSide === void 0) { reverseSide = false; }
  12867. // Culling
  12868. if (this._depthCullingState.cull !== culling || force) {
  12869. this._depthCullingState.cull = culling;
  12870. }
  12871. // Cull face
  12872. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12873. if (this._depthCullingState.cullFace !== cullFace || force) {
  12874. this._depthCullingState.cullFace = cullFace;
  12875. }
  12876. // Z offset
  12877. this.setZOffset(zOffset);
  12878. // Front face
  12879. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12880. if (this._depthCullingState.frontFace !== frontFace || force) {
  12881. this._depthCullingState.frontFace = frontFace;
  12882. }
  12883. };
  12884. Engine.prototype.setZOffset = function (value) {
  12885. this._depthCullingState.zOffset = value;
  12886. };
  12887. Engine.prototype.getZOffset = function () {
  12888. return this._depthCullingState.zOffset;
  12889. };
  12890. Engine.prototype.setDepthBuffer = function (enable) {
  12891. this._depthCullingState.depthTest = enable;
  12892. };
  12893. Engine.prototype.getDepthWrite = function () {
  12894. return this._depthCullingState.depthMask;
  12895. };
  12896. Engine.prototype.setDepthWrite = function (enable) {
  12897. this._depthCullingState.depthMask = enable;
  12898. };
  12899. Engine.prototype.setColorWrite = function (enable) {
  12900. this._gl.colorMask(enable, enable, enable, enable);
  12901. this._colorWrite = enable;
  12902. };
  12903. Engine.prototype.getColorWrite = function () {
  12904. return this._colorWrite;
  12905. };
  12906. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12907. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12908. };
  12909. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12910. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12911. if (this._alphaMode === mode) {
  12912. return;
  12913. }
  12914. switch (mode) {
  12915. case Engine.ALPHA_DISABLE:
  12916. this._alphaState.alphaBlend = false;
  12917. break;
  12918. case Engine.ALPHA_PREMULTIPLIED:
  12919. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12920. this._alphaState.alphaBlend = true;
  12921. break;
  12922. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12923. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12924. this._alphaState.alphaBlend = true;
  12925. break;
  12926. case Engine.ALPHA_COMBINE:
  12927. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12928. this._alphaState.alphaBlend = true;
  12929. break;
  12930. case Engine.ALPHA_ONEONE:
  12931. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12932. this._alphaState.alphaBlend = true;
  12933. break;
  12934. case Engine.ALPHA_ADD:
  12935. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12936. this._alphaState.alphaBlend = true;
  12937. break;
  12938. case Engine.ALPHA_SUBTRACT:
  12939. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12940. this._alphaState.alphaBlend = true;
  12941. break;
  12942. case Engine.ALPHA_MULTIPLY:
  12943. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12944. this._alphaState.alphaBlend = true;
  12945. break;
  12946. case Engine.ALPHA_MAXIMIZED:
  12947. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12948. this._alphaState.alphaBlend = true;
  12949. break;
  12950. case Engine.ALPHA_INTERPOLATE:
  12951. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12952. this._alphaState.alphaBlend = true;
  12953. break;
  12954. case Engine.ALPHA_SCREENMODE:
  12955. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12956. this._alphaState.alphaBlend = true;
  12957. break;
  12958. }
  12959. if (!noDepthWriteChange) {
  12960. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12961. }
  12962. this._alphaMode = mode;
  12963. };
  12964. Engine.prototype.getAlphaMode = function () {
  12965. return this._alphaMode;
  12966. };
  12967. // Textures
  12968. Engine.prototype.wipeCaches = function (bruteForce) {
  12969. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12970. return;
  12971. }
  12972. this._currentEffect = null;
  12973. // 6/8/2017: deltakosh: Should not be required anymore.
  12974. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12975. if (bruteForce) {
  12976. this.resetTextureCache();
  12977. this._currentProgram = null;
  12978. this._stencilState.reset();
  12979. this._depthCullingState.reset();
  12980. this.setDepthFunctionToLessOrEqual();
  12981. this._alphaState.reset();
  12982. }
  12983. this._resetVertexBufferBinding();
  12984. this._cachedIndexBuffer = null;
  12985. this._cachedEffectForVertexBuffers = null;
  12986. this._unbindVertexArrayObject();
  12987. this.bindIndexBuffer(null);
  12988. };
  12989. /**
  12990. * Set the compressed texture format to use, based on the formats you have, and the formats
  12991. * supported by the hardware / browser.
  12992. *
  12993. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12994. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12995. * to API arguments needed to compressed textures. This puts the burden on the container
  12996. * generator to house the arcane code for determining these for current & future formats.
  12997. *
  12998. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12999. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13000. *
  13001. * Note: The result of this call is not taken into account when a texture is base64.
  13002. *
  13003. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13004. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13005. *
  13006. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13007. * @returns The extension selected.
  13008. */
  13009. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13010. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13011. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13012. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13013. return this._textureFormatInUse = this._texturesSupported[i];
  13014. }
  13015. }
  13016. }
  13017. // actively set format to nothing, to allow this to be called more than once
  13018. // and possibly fail the 2nd time
  13019. this._textureFormatInUse = null;
  13020. return null;
  13021. };
  13022. Engine.prototype._createTexture = function () {
  13023. var texture = this._gl.createTexture();
  13024. if (!texture) {
  13025. throw new Error("Unable to create texture");
  13026. }
  13027. return texture;
  13028. };
  13029. /**
  13030. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13031. * @param {string} urlArg- This contains one of the following:
  13032. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13033. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13034. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13035. *
  13036. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13037. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13038. * @param {Scene} scene- Needed for loading to the correct scene.
  13039. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13040. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13041. * @param {callback} onError- Optional callback to be called upon failure.
  13042. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13043. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13044. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13045. *
  13046. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13047. */
  13048. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13049. var _this = this;
  13050. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13051. if (onLoad === void 0) { onLoad = null; }
  13052. if (onError === void 0) { onError = null; }
  13053. if (buffer === void 0) { buffer = null; }
  13054. if (fallBack === void 0) { fallBack = null; }
  13055. if (format === void 0) { format = null; }
  13056. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13057. var fromData = url.substr(0, 5) === "data:";
  13058. var fromBlob = url.substr(0, 5) === "blob:";
  13059. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13060. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13061. // establish the file extension, if possible
  13062. var lastDot = url.lastIndexOf('.');
  13063. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13064. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13065. var isTGA = (extension.indexOf(".tga") === 0);
  13066. // determine if a ktx file should be substituted
  13067. var isKTX = false;
  13068. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13069. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13070. isKTX = true;
  13071. }
  13072. if (scene) {
  13073. scene._addPendingData(texture);
  13074. }
  13075. texture.url = url;
  13076. texture.generateMipMaps = !noMipmap;
  13077. texture.samplingMode = samplingMode;
  13078. texture.invertY = invertY;
  13079. if (!this._doNotHandleContextLost) {
  13080. // Keep a link to the buffer only if we plan to handle context lost
  13081. texture._buffer = buffer;
  13082. }
  13083. var onLoadObserver = null;
  13084. if (onLoad && !fallBack) {
  13085. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13086. }
  13087. if (!fallBack)
  13088. this._internalTexturesCache.push(texture);
  13089. var onerror = function (message, exception) {
  13090. if (scene) {
  13091. scene._removePendingData(texture);
  13092. }
  13093. if (onLoadObserver) {
  13094. texture.onLoadedObservable.remove(onLoadObserver);
  13095. }
  13096. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13097. if (isKTX) {
  13098. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13099. }
  13100. else if (BABYLON.Tools.UseFallbackTexture) {
  13101. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13102. }
  13103. if (onError) {
  13104. onError(message || "Unknown error", exception);
  13105. }
  13106. };
  13107. var callback = null;
  13108. // processing for non-image formats
  13109. if (isKTX || isTGA || isDDS) {
  13110. if (isKTX) {
  13111. callback = function (data) {
  13112. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13113. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13114. ktx.uploadLevels(_this._gl, !noMipmap);
  13115. return false;
  13116. }, samplingMode);
  13117. };
  13118. }
  13119. else if (isTGA) {
  13120. callback = function (arrayBuffer) {
  13121. var data = new Uint8Array(arrayBuffer);
  13122. var header = BABYLON.TGATools.GetTGAHeader(data);
  13123. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13124. BABYLON.TGATools.UploadContent(_this._gl, data);
  13125. return false;
  13126. }, samplingMode);
  13127. };
  13128. }
  13129. else if (isDDS) {
  13130. callback = function (data) {
  13131. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13132. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13133. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13134. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13135. return false;
  13136. }, samplingMode);
  13137. };
  13138. }
  13139. if (!buffer) {
  13140. this._loadFile(url, function (data) {
  13141. if (callback) {
  13142. callback(data);
  13143. }
  13144. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13145. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13146. });
  13147. }
  13148. else {
  13149. if (callback) {
  13150. callback(buffer);
  13151. }
  13152. }
  13153. // image format processing
  13154. }
  13155. else {
  13156. var onload = function (img) {
  13157. if (fromBlob && !_this._doNotHandleContextLost) {
  13158. // We need to store the image if we need to rebuild the texture
  13159. // in case of a webgl context lost
  13160. texture._buffer = img;
  13161. }
  13162. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13163. var gl = _this._gl;
  13164. var isPot = (img.width === potWidth && img.height === potHeight);
  13165. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13166. if (isPot) {
  13167. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13168. return false;
  13169. }
  13170. // Using shaders to rescale because canvas.drawImage is lossy
  13171. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13172. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13173. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13178. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13179. _this._releaseTexture(source);
  13180. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13181. continuationCallback();
  13182. });
  13183. return true;
  13184. }, samplingMode);
  13185. };
  13186. if (!fromData || isBase64)
  13187. if (buffer instanceof HTMLImageElement) {
  13188. onload(buffer);
  13189. }
  13190. else {
  13191. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13192. }
  13193. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13194. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13195. else
  13196. onload(buffer);
  13197. }
  13198. return texture;
  13199. };
  13200. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13201. var _this = this;
  13202. var rtt = this.createRenderTargetTexture({
  13203. width: destination.width,
  13204. height: destination.height,
  13205. }, {
  13206. generateMipMaps: false,
  13207. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13208. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13209. generateDepthBuffer: false,
  13210. generateStencilBuffer: false
  13211. });
  13212. if (!this._rescalePostProcess) {
  13213. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13214. }
  13215. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13216. _this._rescalePostProcess.onApply = function (effect) {
  13217. effect._bindTexture("textureSampler", source);
  13218. };
  13219. var hostingScene = scene;
  13220. if (!hostingScene) {
  13221. hostingScene = _this.scenes[_this.scenes.length - 1];
  13222. }
  13223. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13224. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13225. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13226. _this.unBindFramebuffer(rtt);
  13227. _this._releaseTexture(rtt);
  13228. if (onComplete) {
  13229. onComplete();
  13230. }
  13231. });
  13232. };
  13233. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13234. if (compression === void 0) { compression = null; }
  13235. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13236. if (!texture) {
  13237. return;
  13238. }
  13239. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13240. var internalFormat = this._getInternalFormat(format);
  13241. var textureType = this._getWebGLTextureType(type);
  13242. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13243. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13244. if (!this._doNotHandleContextLost) {
  13245. texture._bufferView = data;
  13246. texture.format = format;
  13247. texture.type = type;
  13248. texture.invertY = invertY;
  13249. texture._compression = compression;
  13250. }
  13251. if (texture.width % 4 !== 0) {
  13252. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13253. }
  13254. if (compression && data) {
  13255. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13256. }
  13257. else {
  13258. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13259. }
  13260. if (texture.generateMipMaps) {
  13261. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13262. }
  13263. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13264. // this.resetTextureCache();
  13265. texture.isReady = true;
  13266. };
  13267. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13268. if (compression === void 0) { compression = null; }
  13269. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13270. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13271. texture.baseWidth = width;
  13272. texture.baseHeight = height;
  13273. texture.width = width;
  13274. texture.height = height;
  13275. texture.format = format;
  13276. texture.generateMipMaps = generateMipMaps;
  13277. texture.samplingMode = samplingMode;
  13278. texture.invertY = invertY;
  13279. texture._compression = compression;
  13280. texture.type = type;
  13281. if (!this._doNotHandleContextLost) {
  13282. texture._bufferView = data;
  13283. }
  13284. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13285. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13286. // Filters
  13287. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13289. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13290. if (generateMipMaps) {
  13291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13292. }
  13293. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13294. this._internalTexturesCache.push(texture);
  13295. return texture;
  13296. };
  13297. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13298. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13299. texture.baseWidth = width;
  13300. texture.baseHeight = height;
  13301. if (generateMipMaps) {
  13302. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13303. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13304. }
  13305. // this.resetTextureCache();
  13306. texture.width = width;
  13307. texture.height = height;
  13308. texture.isReady = false;
  13309. texture.generateMipMaps = generateMipMaps;
  13310. texture.samplingMode = samplingMode;
  13311. this.updateTextureSamplingMode(samplingMode, texture);
  13312. this._internalTexturesCache.push(texture);
  13313. return texture;
  13314. };
  13315. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13316. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13317. if (texture.isCube) {
  13318. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13319. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13320. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13321. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13322. }
  13323. else if (texture.is3D) {
  13324. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13325. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13326. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13327. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13328. }
  13329. else {
  13330. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13333. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13334. }
  13335. texture.samplingMode = samplingMode;
  13336. };
  13337. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13338. if (premulAlpha === void 0) { premulAlpha = false; }
  13339. if (!texture) {
  13340. return;
  13341. }
  13342. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13343. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13344. if (premulAlpha) {
  13345. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13346. }
  13347. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13348. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13349. if (texture.generateMipMaps) {
  13350. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13351. }
  13352. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13353. if (premulAlpha) {
  13354. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13355. }
  13356. texture.isReady = true;
  13357. };
  13358. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13359. if (!texture || texture._isDisabled) {
  13360. return;
  13361. }
  13362. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13363. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13364. try {
  13365. // Testing video texture support
  13366. if (this._videoTextureSupported === undefined) {
  13367. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13368. if (this._gl.getError() !== 0) {
  13369. this._videoTextureSupported = false;
  13370. }
  13371. else {
  13372. this._videoTextureSupported = true;
  13373. }
  13374. }
  13375. // Copy video through the current working canvas if video texture is not supported
  13376. if (!this._videoTextureSupported) {
  13377. if (!texture._workingCanvas) {
  13378. texture._workingCanvas = document.createElement("canvas");
  13379. var context = texture._workingCanvas.getContext("2d");
  13380. if (!context) {
  13381. throw new Error("Unable to get 2d context");
  13382. }
  13383. texture._workingContext = context;
  13384. texture._workingCanvas.width = texture.width;
  13385. texture._workingCanvas.height = texture.height;
  13386. }
  13387. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13388. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13389. }
  13390. else {
  13391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13392. }
  13393. if (texture.generateMipMaps) {
  13394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13395. }
  13396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13397. // this.resetTextureCache();
  13398. texture.isReady = true;
  13399. }
  13400. catch (ex) {
  13401. // Something unexpected
  13402. // Let's disable the texture
  13403. texture._isDisabled = true;
  13404. }
  13405. };
  13406. /**
  13407. * Updates a depth texture Comparison Mode and Function.
  13408. * If the comparison Function is equal to 0, the mode will be set to none.
  13409. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13410. * @param texture The texture to set the comparison function for
  13411. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13412. */
  13413. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13414. if (this.webGLVersion === 1) {
  13415. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13416. return;
  13417. }
  13418. var gl = this._gl;
  13419. if (texture.isCube) {
  13420. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13421. if (comparisonFunction === 0) {
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13424. }
  13425. else {
  13426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13428. }
  13429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13430. }
  13431. else {
  13432. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13433. if (comparisonFunction === 0) {
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13436. }
  13437. else {
  13438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13440. }
  13441. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13442. }
  13443. texture._comparisonFunction = comparisonFunction;
  13444. };
  13445. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13446. var width = size.width || size;
  13447. var height = size.height || size;
  13448. internalTexture.baseWidth = width;
  13449. internalTexture.baseHeight = height;
  13450. internalTexture.width = width;
  13451. internalTexture.height = height;
  13452. internalTexture.isReady = true;
  13453. internalTexture.samples = 1;
  13454. internalTexture.generateMipMaps = false;
  13455. internalTexture._generateDepthBuffer = true;
  13456. internalTexture._generateStencilBuffer = generateStencil;
  13457. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13458. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13459. internalTexture._comparisonFunction = comparisonFunction;
  13460. var gl = this._gl;
  13461. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13462. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13463. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13464. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13465. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13466. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13467. if (comparisonFunction === 0) {
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13469. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13470. }
  13471. else {
  13472. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13473. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13474. }
  13475. };
  13476. /**
  13477. * Creates a depth stencil texture.
  13478. * This is only available in WebGL 2 or with the depth texture extension available.
  13479. * @param size The size of face edge in the texture.
  13480. * @param options The options defining the texture.
  13481. * @returns The texture
  13482. */
  13483. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13484. if (options.isCube) {
  13485. var width = size.width || size;
  13486. return this._createDepthStencilCubeTexture(width, options);
  13487. }
  13488. else {
  13489. return this._createDepthStencilTexture(size, options);
  13490. }
  13491. };
  13492. /**
  13493. * Creates a depth stencil texture.
  13494. * This is only available in WebGL 2 or with the depth texture extension available.
  13495. * @param size The size of face edge in the texture.
  13496. * @param options The options defining the texture.
  13497. * @returns The texture
  13498. */
  13499. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13500. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13501. if (!this._caps.depthTextureExtension) {
  13502. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13503. return internalTexture;
  13504. }
  13505. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13506. var gl = this._gl;
  13507. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13508. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13509. if (this.webGLVersion > 1) {
  13510. if (internalOptions.generateStencil) {
  13511. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13512. }
  13513. else {
  13514. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13515. }
  13516. }
  13517. else {
  13518. if (internalOptions.generateStencil) {
  13519. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13520. }
  13521. else {
  13522. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13523. }
  13524. }
  13525. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13526. return internalTexture;
  13527. };
  13528. /**
  13529. * Creates a depth stencil cube texture.
  13530. * This is only available in WebGL 2.
  13531. * @param size The size of face edge in the cube texture.
  13532. * @param options The options defining the cube texture.
  13533. * @returns The cube texture
  13534. */
  13535. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13536. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13537. internalTexture.isCube = true;
  13538. if (this.webGLVersion === 1) {
  13539. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13540. return internalTexture;
  13541. }
  13542. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13543. var gl = this._gl;
  13544. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13545. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13546. // Create the depth/stencil buffer
  13547. for (var face = 0; face < 6; face++) {
  13548. if (internalOptions.generateStencil) {
  13549. 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);
  13550. }
  13551. else {
  13552. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13553. }
  13554. }
  13555. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13556. return internalTexture;
  13557. };
  13558. /**
  13559. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13560. * @param renderTarget The render target to set the frame buffer for
  13561. */
  13562. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13563. // Create the framebuffer
  13564. var internalTexture = renderTarget.getInternalTexture();
  13565. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13566. return;
  13567. }
  13568. var gl = this._gl;
  13569. var depthStencilTexture = renderTarget.depthStencilTexture;
  13570. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13571. if (depthStencilTexture.isCube) {
  13572. if (depthStencilTexture._generateStencilBuffer) {
  13573. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13574. }
  13575. else {
  13576. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13577. }
  13578. }
  13579. else {
  13580. if (depthStencilTexture._generateStencilBuffer) {
  13581. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13582. }
  13583. else {
  13584. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13585. }
  13586. }
  13587. this.bindUnboundFramebuffer(null);
  13588. };
  13589. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13590. var fullOptions = new RenderTargetCreationOptions();
  13591. if (options !== undefined && typeof options === "object") {
  13592. fullOptions.generateMipMaps = options.generateMipMaps;
  13593. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13594. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13595. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13596. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13597. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13598. }
  13599. else {
  13600. fullOptions.generateMipMaps = options;
  13601. fullOptions.generateDepthBuffer = true;
  13602. fullOptions.generateStencilBuffer = false;
  13603. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13604. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13605. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13606. }
  13607. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13608. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13609. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13610. }
  13611. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13612. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13613. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13614. }
  13615. var gl = this._gl;
  13616. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13617. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13618. var width = size.width || size;
  13619. var height = size.height || size;
  13620. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13621. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13622. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13623. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13624. }
  13625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13628. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13629. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13630. // Create the framebuffer
  13631. var framebuffer = gl.createFramebuffer();
  13632. this.bindUnboundFramebuffer(framebuffer);
  13633. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13634. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13635. if (fullOptions.generateMipMaps) {
  13636. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13637. }
  13638. // Unbind
  13639. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13640. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13641. this.bindUnboundFramebuffer(null);
  13642. texture._framebuffer = framebuffer;
  13643. texture.baseWidth = width;
  13644. texture.baseHeight = height;
  13645. texture.width = width;
  13646. texture.height = height;
  13647. texture.isReady = true;
  13648. texture.samples = 1;
  13649. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13650. texture.samplingMode = fullOptions.samplingMode;
  13651. texture.type = fullOptions.type;
  13652. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13653. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13654. // this.resetTextureCache();
  13655. this._internalTexturesCache.push(texture);
  13656. return texture;
  13657. };
  13658. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13659. var generateMipMaps = false;
  13660. var generateDepthBuffer = true;
  13661. var generateStencilBuffer = false;
  13662. var generateDepthTexture = false;
  13663. var textureCount = 1;
  13664. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13665. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13666. var types = [], samplingModes = [];
  13667. if (options !== undefined) {
  13668. generateMipMaps = options.generateMipMaps;
  13669. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13670. generateStencilBuffer = options.generateStencilBuffer;
  13671. generateDepthTexture = options.generateDepthTexture;
  13672. textureCount = options.textureCount || 1;
  13673. if (options.types) {
  13674. types = options.types;
  13675. }
  13676. if (options.samplingModes) {
  13677. samplingModes = options.samplingModes;
  13678. }
  13679. }
  13680. var gl = this._gl;
  13681. // Create the framebuffer
  13682. var framebuffer = gl.createFramebuffer();
  13683. this.bindUnboundFramebuffer(framebuffer);
  13684. var width = size.width || size;
  13685. var height = size.height || size;
  13686. var textures = [];
  13687. var attachments = [];
  13688. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13689. for (var i = 0; i < textureCount; i++) {
  13690. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13691. var type = types[i] || defaultType;
  13692. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13693. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13694. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13695. }
  13696. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13697. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13698. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13699. }
  13700. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13701. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13702. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13703. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13704. }
  13705. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13706. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13707. textures.push(texture);
  13708. attachments.push(attachment);
  13709. gl.activeTexture(gl["TEXTURE" + i]);
  13710. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13714. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13715. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13716. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13717. if (generateMipMaps) {
  13718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13719. }
  13720. // Unbind
  13721. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13722. texture._framebuffer = framebuffer;
  13723. texture._depthStencilBuffer = depthStencilBuffer;
  13724. texture.baseWidth = width;
  13725. texture.baseHeight = height;
  13726. texture.width = width;
  13727. texture.height = height;
  13728. texture.isReady = true;
  13729. texture.samples = 1;
  13730. texture.generateMipMaps = generateMipMaps;
  13731. texture.samplingMode = samplingMode;
  13732. texture.type = type;
  13733. texture._generateDepthBuffer = generateDepthBuffer;
  13734. texture._generateStencilBuffer = generateStencilBuffer;
  13735. texture._attachments = attachments;
  13736. this._internalTexturesCache.push(texture);
  13737. }
  13738. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13739. // Depth texture
  13740. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13741. gl.activeTexture(gl.TEXTURE0);
  13742. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13746. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13747. 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);
  13748. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13749. depthTexture._framebuffer = framebuffer;
  13750. depthTexture.baseWidth = width;
  13751. depthTexture.baseHeight = height;
  13752. depthTexture.width = width;
  13753. depthTexture.height = height;
  13754. depthTexture.isReady = true;
  13755. depthTexture.samples = 1;
  13756. depthTexture.generateMipMaps = generateMipMaps;
  13757. depthTexture.samplingMode = gl.NEAREST;
  13758. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13759. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13760. textures.push(depthTexture);
  13761. this._internalTexturesCache.push(depthTexture);
  13762. }
  13763. gl.drawBuffers(attachments);
  13764. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13765. this.bindUnboundFramebuffer(null);
  13766. this.resetTextureCache();
  13767. return textures;
  13768. };
  13769. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13770. if (samples === void 0) { samples = 1; }
  13771. var depthStencilBuffer = null;
  13772. var gl = this._gl;
  13773. // Create the depth/stencil buffer
  13774. if (generateStencilBuffer) {
  13775. depthStencilBuffer = gl.createRenderbuffer();
  13776. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13777. if (samples > 1) {
  13778. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13779. }
  13780. else {
  13781. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13782. }
  13783. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13784. }
  13785. else if (generateDepthBuffer) {
  13786. depthStencilBuffer = gl.createRenderbuffer();
  13787. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13788. if (samples > 1) {
  13789. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13790. }
  13791. else {
  13792. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13793. }
  13794. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13795. }
  13796. return depthStencilBuffer;
  13797. };
  13798. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13799. if (this.webGLVersion < 2 || !texture) {
  13800. return 1;
  13801. }
  13802. if (texture.samples === samples) {
  13803. return samples;
  13804. }
  13805. var gl = this._gl;
  13806. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13807. // Dispose previous render buffers
  13808. if (texture._depthStencilBuffer) {
  13809. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13810. texture._depthStencilBuffer = null;
  13811. }
  13812. if (texture._MSAAFramebuffer) {
  13813. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13814. texture._MSAAFramebuffer = null;
  13815. }
  13816. if (texture._MSAARenderBuffer) {
  13817. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13818. texture._MSAARenderBuffer = null;
  13819. }
  13820. if (samples > 1) {
  13821. var framebuffer = gl.createFramebuffer();
  13822. if (!framebuffer) {
  13823. throw new Error("Unable to create multi sampled framebuffer");
  13824. }
  13825. texture._MSAAFramebuffer = framebuffer;
  13826. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13827. var colorRenderbuffer = gl.createRenderbuffer();
  13828. if (!colorRenderbuffer) {
  13829. throw new Error("Unable to create multi sampled framebuffer");
  13830. }
  13831. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13832. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13833. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13834. texture._MSAARenderBuffer = colorRenderbuffer;
  13835. }
  13836. else {
  13837. this.bindUnboundFramebuffer(texture._framebuffer);
  13838. }
  13839. texture.samples = samples;
  13840. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13841. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13842. this.bindUnboundFramebuffer(null);
  13843. return samples;
  13844. };
  13845. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13846. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13847. return 1;
  13848. }
  13849. if (textures[0].samples === samples) {
  13850. return samples;
  13851. }
  13852. var gl = this._gl;
  13853. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13854. // Dispose previous render buffers
  13855. if (textures[0]._depthStencilBuffer) {
  13856. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13857. textures[0]._depthStencilBuffer = null;
  13858. }
  13859. if (textures[0]._MSAAFramebuffer) {
  13860. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13861. textures[0]._MSAAFramebuffer = null;
  13862. }
  13863. for (var i = 0; i < textures.length; i++) {
  13864. if (textures[i]._MSAARenderBuffer) {
  13865. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13866. textures[i]._MSAARenderBuffer = null;
  13867. }
  13868. }
  13869. if (samples > 1) {
  13870. var framebuffer = gl.createFramebuffer();
  13871. if (!framebuffer) {
  13872. throw new Error("Unable to create multi sampled framebuffer");
  13873. }
  13874. this.bindUnboundFramebuffer(framebuffer);
  13875. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13876. var attachments = [];
  13877. for (var i = 0; i < textures.length; i++) {
  13878. var texture = textures[i];
  13879. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13880. var colorRenderbuffer = gl.createRenderbuffer();
  13881. if (!colorRenderbuffer) {
  13882. throw new Error("Unable to create multi sampled framebuffer");
  13883. }
  13884. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13885. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13886. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13887. texture._MSAAFramebuffer = framebuffer;
  13888. texture._MSAARenderBuffer = colorRenderbuffer;
  13889. texture.samples = samples;
  13890. texture._depthStencilBuffer = depthStencilBuffer;
  13891. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13892. attachments.push(attachment);
  13893. }
  13894. gl.drawBuffers(attachments);
  13895. }
  13896. else {
  13897. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13898. }
  13899. this.bindUnboundFramebuffer(null);
  13900. return samples;
  13901. };
  13902. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13903. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13904. };
  13905. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13906. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13907. };
  13908. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13909. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13910. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13911. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13912. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13913. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13914. }
  13915. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13916. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13917. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13918. }
  13919. var gl = this._gl;
  13920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13922. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13923. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13924. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13925. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13926. }
  13927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13930. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13931. for (var face = 0; face < 6; face++) {
  13932. 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);
  13933. }
  13934. // Create the framebuffer
  13935. var framebuffer = gl.createFramebuffer();
  13936. this.bindUnboundFramebuffer(framebuffer);
  13937. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13938. // MipMaps
  13939. if (fullOptions.generateMipMaps) {
  13940. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13941. }
  13942. // Unbind
  13943. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13944. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13945. this.bindUnboundFramebuffer(null);
  13946. texture._framebuffer = framebuffer;
  13947. texture.width = size;
  13948. texture.height = size;
  13949. texture.isReady = true;
  13950. texture.isCube = true;
  13951. texture.samples = 1;
  13952. texture.generateMipMaps = fullOptions.generateMipMaps;
  13953. texture.samplingMode = fullOptions.samplingMode;
  13954. texture.type = fullOptions.type;
  13955. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13956. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13957. this._internalTexturesCache.push(texture);
  13958. return texture;
  13959. };
  13960. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13961. var _this = this;
  13962. if (onLoad === void 0) { onLoad = null; }
  13963. if (onError === void 0) { onError = null; }
  13964. if (forcedExtension === void 0) { forcedExtension = null; }
  13965. var callback = function (loadData) {
  13966. if (!loadData) {
  13967. if (onLoad) {
  13968. onLoad(null);
  13969. }
  13970. return;
  13971. }
  13972. var texture = loadData.texture;
  13973. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13974. texture._lodGenerationScale = scale;
  13975. texture._lodGenerationOffset = offset;
  13976. if (_this._caps.textureLOD) {
  13977. // Do not add extra process if texture lod is supported.
  13978. if (onLoad) {
  13979. onLoad(texture);
  13980. }
  13981. return;
  13982. }
  13983. var mipSlices = 3;
  13984. var gl = _this._gl;
  13985. var width = loadData.width;
  13986. if (!width) {
  13987. return;
  13988. }
  13989. var textures = [];
  13990. for (var i = 0; i < mipSlices; i++) {
  13991. //compute LOD from even spacing in smoothness (matching shader calculation)
  13992. var smoothness = i / (mipSlices - 1);
  13993. var roughness = 1 - smoothness;
  13994. var minLODIndex = offset; // roughness = 0
  13995. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13996. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13997. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13998. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13999. glTextureFromLod.isCube = true;
  14000. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14004. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14005. if (loadData.isDDS) {
  14006. var info = loadData.info;
  14007. var data = loadData.data;
  14008. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14009. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14010. }
  14011. else {
  14012. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14013. }
  14014. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14015. // Wrap in a base texture for easy binding.
  14016. var lodTexture = new BABYLON.BaseTexture(scene);
  14017. lodTexture.isCube = true;
  14018. lodTexture._texture = glTextureFromLod;
  14019. glTextureFromLod.isReady = true;
  14020. textures.push(lodTexture);
  14021. }
  14022. texture._lodTextureHigh = textures[2];
  14023. texture._lodTextureMid = textures[1];
  14024. texture._lodTextureLow = textures[0];
  14025. if (onLoad) {
  14026. onLoad(texture);
  14027. }
  14028. };
  14029. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14030. };
  14031. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14032. var _this = this;
  14033. if (onLoad === void 0) { onLoad = null; }
  14034. if (onError === void 0) { onError = null; }
  14035. if (forcedExtension === void 0) { forcedExtension = null; }
  14036. var gl = this._gl;
  14037. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14038. texture.isCube = true;
  14039. texture.url = rootUrl;
  14040. texture.generateMipMaps = !noMipmap;
  14041. if (!this._doNotHandleContextLost) {
  14042. texture._extension = forcedExtension;
  14043. texture._files = files;
  14044. }
  14045. var isKTX = false;
  14046. var isDDS = false;
  14047. var lastDot = rootUrl.lastIndexOf('.');
  14048. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14049. if (this._textureFormatInUse) {
  14050. extension = this._textureFormatInUse;
  14051. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14052. isKTX = true;
  14053. }
  14054. else {
  14055. isDDS = (extension === ".dds");
  14056. }
  14057. var onerror = function (request, exception) {
  14058. if (onError && request) {
  14059. onError(request.status + " " + request.statusText, exception);
  14060. }
  14061. };
  14062. if (isKTX) {
  14063. this._loadFile(rootUrl, function (data) {
  14064. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14065. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14066. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14068. ktx.uploadLevels(_this._gl, !noMipmap);
  14069. _this.setCubeMapTextureParams(gl, loadMipmap);
  14070. texture.width = ktx.pixelWidth;
  14071. texture.height = ktx.pixelHeight;
  14072. texture.isReady = true;
  14073. }, undefined, undefined, true, onerror);
  14074. }
  14075. else if (isDDS) {
  14076. if (files && files.length === 6) {
  14077. this._cascadeLoadFiles(scene, function (imgs) {
  14078. var info;
  14079. var loadMipmap = false;
  14080. var width = 0;
  14081. for (var index = 0; index < imgs.length; index++) {
  14082. var data = imgs[index];
  14083. info = BABYLON.DDSTools.GetDDSInfo(data);
  14084. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14085. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14086. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14087. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14088. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14089. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14090. }
  14091. texture.width = info.width;
  14092. texture.height = info.height;
  14093. texture.type = info.textureType;
  14094. width = info.width;
  14095. }
  14096. _this.setCubeMapTextureParams(gl, loadMipmap);
  14097. texture.isReady = true;
  14098. if (onLoad) {
  14099. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14100. }
  14101. }, files, onError);
  14102. }
  14103. else {
  14104. this._loadFile(rootUrl, function (data) {
  14105. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14106. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14107. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14108. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14109. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14110. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14111. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14112. }
  14113. _this.setCubeMapTextureParams(gl, loadMipmap);
  14114. texture.width = info.width;
  14115. texture.height = info.height;
  14116. texture.isReady = true;
  14117. texture.type = info.textureType;
  14118. if (onLoad) {
  14119. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14120. }
  14121. }, undefined, undefined, true, onerror);
  14122. }
  14123. }
  14124. else {
  14125. if (!files) {
  14126. throw new Error("Cannot load cubemap because files were not defined");
  14127. }
  14128. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14129. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14130. var height = width;
  14131. _this._prepareWorkingCanvas();
  14132. if (!_this._workingCanvas || !_this._workingContext) {
  14133. return;
  14134. }
  14135. _this._workingCanvas.width = width;
  14136. _this._workingCanvas.height = height;
  14137. var faces = [
  14138. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14139. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14140. ];
  14141. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14142. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14143. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14144. for (var index = 0; index < faces.length; index++) {
  14145. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14146. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14147. }
  14148. if (!noMipmap) {
  14149. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14150. }
  14151. _this.setCubeMapTextureParams(gl, !noMipmap);
  14152. texture.width = width;
  14153. texture.height = height;
  14154. texture.isReady = true;
  14155. if (format) {
  14156. texture.format = format;
  14157. }
  14158. texture.onLoadedObservable.notifyObservers(texture);
  14159. texture.onLoadedObservable.clear();
  14160. if (onLoad) {
  14161. onLoad();
  14162. }
  14163. }, files, onError);
  14164. }
  14165. this._internalTexturesCache.push(texture);
  14166. return texture;
  14167. };
  14168. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14172. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14173. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14174. // this.resetTextureCache();
  14175. };
  14176. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14177. if (compression === void 0) { compression = null; }
  14178. if (level === void 0) { level = 0; }
  14179. texture._bufferViewArray = data;
  14180. texture.format = format;
  14181. texture.type = type;
  14182. texture.invertY = invertY;
  14183. texture._compression = compression;
  14184. var gl = this._gl;
  14185. var textureType = this._getWebGLTextureType(type);
  14186. var internalFormat = this._getInternalFormat(format);
  14187. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14188. var needConversion = false;
  14189. if (internalFormat === gl.RGB) {
  14190. internalFormat = gl.RGBA;
  14191. needConversion = true;
  14192. }
  14193. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14194. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14195. if (texture.width % 4 !== 0) {
  14196. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14197. }
  14198. // Data are known to be in +X +Y +Z -X -Y -Z
  14199. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14200. var faceData = data[faceIndex];
  14201. if (compression) {
  14202. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14203. }
  14204. else {
  14205. if (needConversion) {
  14206. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14207. }
  14208. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14209. }
  14210. }
  14211. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14212. if (isPot && texture.generateMipMaps && level === 0) {
  14213. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14214. }
  14215. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14216. // this.resetTextureCache();
  14217. texture.isReady = true;
  14218. };
  14219. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14220. if (compression === void 0) { compression = null; }
  14221. var gl = this._gl;
  14222. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14223. texture.isCube = true;
  14224. texture.generateMipMaps = generateMipMaps;
  14225. texture.format = format;
  14226. texture.type = type;
  14227. if (!this._doNotHandleContextLost) {
  14228. texture._bufferViewArray = data;
  14229. }
  14230. var textureType = this._getWebGLTextureType(type);
  14231. var internalFormat = this._getInternalFormat(format);
  14232. if (internalFormat === gl.RGB) {
  14233. internalFormat = gl.RGBA;
  14234. }
  14235. var width = size;
  14236. var height = width;
  14237. texture.width = width;
  14238. texture.height = height;
  14239. // Double check on POT to generate Mips.
  14240. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14241. if (!isPot) {
  14242. generateMipMaps = false;
  14243. }
  14244. // Upload data if needed. The texture won't be ready until then.
  14245. if (data) {
  14246. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14247. }
  14248. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14249. // Filters
  14250. if (data && generateMipMaps) {
  14251. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14252. }
  14253. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14255. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14256. }
  14257. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14259. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14260. }
  14261. else {
  14262. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14264. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14265. }
  14266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14268. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14269. return texture;
  14270. };
  14271. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14272. var _this = this;
  14273. if (onLoad === void 0) { onLoad = null; }
  14274. if (onError === void 0) { onError = null; }
  14275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14276. if (invertY === void 0) { invertY = false; }
  14277. var gl = this._gl;
  14278. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14279. scene._addPendingData(texture);
  14280. texture.url = url;
  14281. this._internalTexturesCache.push(texture);
  14282. var onerror = function (request, exception) {
  14283. scene._removePendingData(texture);
  14284. if (onError && request) {
  14285. onError(request.status + " " + request.statusText, exception);
  14286. }
  14287. };
  14288. var internalCallback = function (data) {
  14289. var width = texture.width;
  14290. var faceDataArrays = callback(data);
  14291. if (!faceDataArrays) {
  14292. return;
  14293. }
  14294. if (mipmmapGenerator) {
  14295. var textureType = _this._getWebGLTextureType(type);
  14296. var internalFormat = _this._getInternalFormat(format);
  14297. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14298. var needConversion = false;
  14299. if (internalFormat === gl.RGB) {
  14300. internalFormat = gl.RGBA;
  14301. needConversion = true;
  14302. }
  14303. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14304. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14305. var mipData = mipmmapGenerator(faceDataArrays);
  14306. for (var level = 0; level < mipData.length; level++) {
  14307. var mipSize = width >> level;
  14308. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14309. var mipFaceData = mipData[level][faceIndex];
  14310. if (needConversion) {
  14311. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14312. }
  14313. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14314. }
  14315. }
  14316. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14317. }
  14318. else {
  14319. texture.generateMipMaps = !noMipmap;
  14320. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14321. }
  14322. texture.isReady = true;
  14323. // this.resetTextureCache();
  14324. scene._removePendingData(texture);
  14325. if (onLoad) {
  14326. onLoad();
  14327. }
  14328. };
  14329. this._loadFile(url, function (data) {
  14330. internalCallback(data);
  14331. }, undefined, scene.database, true, onerror);
  14332. return texture;
  14333. };
  14334. ;
  14335. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14336. if (compression === void 0) { compression = null; }
  14337. var internalFormat = this._getInternalFormat(format);
  14338. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14339. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14340. if (!this._doNotHandleContextLost) {
  14341. texture._bufferView = data;
  14342. texture.format = format;
  14343. texture.invertY = invertY;
  14344. texture._compression = compression;
  14345. }
  14346. if (texture.width % 4 !== 0) {
  14347. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14348. }
  14349. if (compression && data) {
  14350. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14351. }
  14352. else {
  14353. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14354. }
  14355. if (texture.generateMipMaps) {
  14356. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14357. }
  14358. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14359. // this.resetTextureCache();
  14360. texture.isReady = true;
  14361. };
  14362. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14363. if (compression === void 0) { compression = null; }
  14364. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14365. texture.baseWidth = width;
  14366. texture.baseHeight = height;
  14367. texture.baseDepth = depth;
  14368. texture.width = width;
  14369. texture.height = height;
  14370. texture.depth = depth;
  14371. texture.format = format;
  14372. texture.generateMipMaps = generateMipMaps;
  14373. texture.samplingMode = samplingMode;
  14374. texture.is3D = true;
  14375. if (!this._doNotHandleContextLost) {
  14376. texture._bufferView = data;
  14377. }
  14378. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14379. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14380. // Filters
  14381. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14382. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14383. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14384. if (generateMipMaps) {
  14385. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14386. }
  14387. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14388. this._internalTexturesCache.push(texture);
  14389. return texture;
  14390. };
  14391. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14392. var gl = this._gl;
  14393. if (!gl) {
  14394. return;
  14395. }
  14396. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14398. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14399. if (!noMipmap && !isCompressed) {
  14400. gl.generateMipmap(gl.TEXTURE_2D);
  14401. }
  14402. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14403. // this.resetTextureCache();
  14404. if (scene) {
  14405. scene._removePendingData(texture);
  14406. }
  14407. texture.onLoadedObservable.notifyObservers(texture);
  14408. texture.onLoadedObservable.clear();
  14409. };
  14410. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14411. var _this = this;
  14412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14413. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14414. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14415. var gl = this._gl;
  14416. if (!gl) {
  14417. return;
  14418. }
  14419. if (!texture._webGLTexture) {
  14420. // this.resetTextureCache();
  14421. if (scene) {
  14422. scene._removePendingData(texture);
  14423. }
  14424. return;
  14425. }
  14426. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14428. texture.baseWidth = width;
  14429. texture.baseHeight = height;
  14430. texture.width = potWidth;
  14431. texture.height = potHeight;
  14432. texture.isReady = true;
  14433. if (processFunction(potWidth, potHeight, function () {
  14434. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14435. })) {
  14436. // Returning as texture needs extra async steps
  14437. return;
  14438. }
  14439. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14440. };
  14441. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14442. // Create new RGBA data container.
  14443. var rgbaData;
  14444. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14445. rgbaData = new Float32Array(width * height * 4);
  14446. }
  14447. else {
  14448. rgbaData = new Uint32Array(width * height * 4);
  14449. }
  14450. // Convert each pixel.
  14451. for (var x = 0; x < width; x++) {
  14452. for (var y = 0; y < height; y++) {
  14453. var index = (y * width + x) * 3;
  14454. var newIndex = (y * width + x) * 4;
  14455. // Map Old Value to new value.
  14456. rgbaData[newIndex + 0] = rgbData[index + 0];
  14457. rgbaData[newIndex + 1] = rgbData[index + 1];
  14458. rgbaData[newIndex + 2] = rgbData[index + 2];
  14459. // Add fully opaque alpha channel.
  14460. rgbaData[newIndex + 3] = 1;
  14461. }
  14462. }
  14463. return rgbaData;
  14464. };
  14465. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14466. var gl = this._gl;
  14467. if (texture._framebuffer) {
  14468. gl.deleteFramebuffer(texture._framebuffer);
  14469. texture._framebuffer = null;
  14470. }
  14471. if (texture._depthStencilBuffer) {
  14472. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14473. texture._depthStencilBuffer = null;
  14474. }
  14475. if (texture._MSAAFramebuffer) {
  14476. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14477. texture._MSAAFramebuffer = null;
  14478. }
  14479. if (texture._MSAARenderBuffer) {
  14480. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14481. texture._MSAARenderBuffer = null;
  14482. }
  14483. };
  14484. Engine.prototype._releaseTexture = function (texture) {
  14485. var gl = this._gl;
  14486. this._releaseFramebufferObjects(texture);
  14487. gl.deleteTexture(texture._webGLTexture);
  14488. // Unbind channels
  14489. this.unbindAllTextures();
  14490. var index = this._internalTexturesCache.indexOf(texture);
  14491. if (index !== -1) {
  14492. this._internalTexturesCache.splice(index, 1);
  14493. }
  14494. // Integrated fixed lod samplers.
  14495. if (texture._lodTextureHigh) {
  14496. texture._lodTextureHigh.dispose();
  14497. }
  14498. if (texture._lodTextureMid) {
  14499. texture._lodTextureMid.dispose();
  14500. }
  14501. if (texture._lodTextureLow) {
  14502. texture._lodTextureLow.dispose();
  14503. }
  14504. // Set output texture of post process to null if the texture has been released/disposed
  14505. this.scenes.forEach(function (scene) {
  14506. scene.postProcesses.forEach(function (postProcess) {
  14507. if (postProcess._outputTexture == texture) {
  14508. postProcess._outputTexture = null;
  14509. }
  14510. });
  14511. scene.cameras.forEach(function (camera) {
  14512. camera._postProcesses.forEach(function (postProcess) {
  14513. if (postProcess) {
  14514. if (postProcess._outputTexture == texture) {
  14515. postProcess._outputTexture = null;
  14516. }
  14517. }
  14518. });
  14519. });
  14520. });
  14521. };
  14522. Engine.prototype.setProgram = function (program) {
  14523. if (this._currentProgram !== program) {
  14524. this._gl.useProgram(program);
  14525. this._currentProgram = program;
  14526. }
  14527. };
  14528. Engine.prototype.bindSamplers = function (effect) {
  14529. this.setProgram(effect.getProgram());
  14530. var samplers = effect.getSamplers();
  14531. for (var index = 0; index < samplers.length; index++) {
  14532. var uniform = effect.getUniform(samplers[index]);
  14533. if (uniform) {
  14534. this._boundUniforms[index] = uniform;
  14535. }
  14536. }
  14537. this._currentEffect = null;
  14538. };
  14539. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14540. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14541. return;
  14542. }
  14543. // Remove
  14544. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14545. // Bind last to it
  14546. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14547. // Bind to dummy
  14548. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14549. };
  14550. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14551. if (!internalTexture) {
  14552. return -1;
  14553. }
  14554. internalTexture._initialSlot = channel;
  14555. if (this.disableTextureBindingOptimization) {
  14556. if (channel !== internalTexture._designatedSlot) {
  14557. this._textureCollisions.addCount(1, false);
  14558. }
  14559. }
  14560. else {
  14561. if (channel !== internalTexture._designatedSlot) {
  14562. if (internalTexture._designatedSlot > -1) {
  14563. return internalTexture._designatedSlot;
  14564. }
  14565. else {
  14566. // No slot for this texture, let's pick a new one (if we find a free slot)
  14567. if (this._nextFreeTextureSlots.length) {
  14568. return this._nextFreeTextureSlots[0];
  14569. }
  14570. // We need to recycle the oldest bound texture, sorry.
  14571. this._textureCollisions.addCount(1, false);
  14572. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14573. }
  14574. }
  14575. }
  14576. return channel;
  14577. };
  14578. Engine.prototype._linkTrackers = function (previous, next) {
  14579. previous.next = next;
  14580. next.previous = previous;
  14581. };
  14582. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14583. var currentSlot = internalTexture._designatedSlot;
  14584. if (currentSlot === -1) {
  14585. return -1;
  14586. }
  14587. internalTexture._designatedSlot = -1;
  14588. if (this.disableTextureBindingOptimization) {
  14589. return -1;
  14590. }
  14591. // Remove from bound list
  14592. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14593. // Free the slot
  14594. this._boundTexturesCache[currentSlot] = null;
  14595. this._nextFreeTextureSlots.push(currentSlot);
  14596. return currentSlot;
  14597. };
  14598. Engine.prototype._activateCurrentTexture = function () {
  14599. if (this._currentTextureChannel !== this._activeChannel) {
  14600. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14601. this._currentTextureChannel = this._activeChannel;
  14602. }
  14603. };
  14604. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14605. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14606. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14607. this._activeChannel = texture._designatedSlot;
  14608. }
  14609. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14610. var isTextureForRendering = texture && texture._initialSlot > -1;
  14611. if (currentTextureBound !== texture) {
  14612. if (currentTextureBound) {
  14613. this._removeDesignatedSlot(currentTextureBound);
  14614. }
  14615. this._activateCurrentTexture();
  14616. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14617. this._boundTexturesCache[this._activeChannel] = texture;
  14618. if (texture) {
  14619. if (!this.disableTextureBindingOptimization) {
  14620. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14621. if (slotIndex > -1) {
  14622. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14623. }
  14624. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14625. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14626. }
  14627. texture._designatedSlot = this._activeChannel;
  14628. }
  14629. }
  14630. else if (forTextureDataUpdate) {
  14631. this._activateCurrentTexture();
  14632. }
  14633. if (isTextureForRendering && !forTextureDataUpdate) {
  14634. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14635. }
  14636. };
  14637. Engine.prototype._bindTexture = function (channel, texture) {
  14638. if (channel < 0) {
  14639. return;
  14640. }
  14641. if (texture) {
  14642. channel = this._getCorrectTextureChannel(channel, texture);
  14643. }
  14644. this._activeChannel = channel;
  14645. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14646. };
  14647. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14648. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14649. };
  14650. /**
  14651. * Binds the output of the passed in post process to the texture channel specified
  14652. * @param channel The channel the texture should be bound to
  14653. * @param postProcess The post process which's output should be bound
  14654. */
  14655. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14656. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14657. };
  14658. Engine.prototype.unbindAllTextures = function () {
  14659. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14660. this._activeChannel = channel;
  14661. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14663. if (this.webGLVersion > 1) {
  14664. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14665. }
  14666. }
  14667. };
  14668. /**
  14669. * Sets a texture to the according uniform.
  14670. * @param channel The texture channel
  14671. * @param uniform The uniform to set
  14672. * @param texture The texture to apply
  14673. */
  14674. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14675. if (channel < 0) {
  14676. return;
  14677. }
  14678. if (uniform) {
  14679. this._boundUniforms[channel] = uniform;
  14680. }
  14681. this._setTexture(channel, texture);
  14682. };
  14683. /**
  14684. * Sets a depth stencil texture from a render target to the according uniform.
  14685. * @param channel The texture channel
  14686. * @param uniform The uniform to set
  14687. * @param texture The render target texture containing the depth stencil texture to apply
  14688. */
  14689. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14690. if (channel < 0) {
  14691. return;
  14692. }
  14693. if (uniform) {
  14694. this._boundUniforms[channel] = uniform;
  14695. }
  14696. if (!texture || !texture.depthStencilTexture) {
  14697. this._setTexture(channel, null);
  14698. }
  14699. else {
  14700. this._setTexture(channel, texture, false, true);
  14701. }
  14702. };
  14703. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14704. var uniform = this._boundUniforms[sourceSlot];
  14705. if (uniform._currentState === destination) {
  14706. return;
  14707. }
  14708. this._gl.uniform1i(uniform, destination);
  14709. uniform._currentState = destination;
  14710. };
  14711. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14712. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14713. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14714. // Not ready?
  14715. if (!texture) {
  14716. if (this._boundTexturesCache[channel] != null) {
  14717. this._activeChannel = channel;
  14718. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14719. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14720. if (this.webGLVersion > 1) {
  14721. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14722. }
  14723. }
  14724. return false;
  14725. }
  14726. // Video
  14727. if (texture.video) {
  14728. this._activeChannel = channel;
  14729. texture.update();
  14730. }
  14731. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14732. texture.delayLoad();
  14733. return false;
  14734. }
  14735. var internalTexture;
  14736. if (depthStencilTexture) {
  14737. internalTexture = texture.depthStencilTexture;
  14738. }
  14739. else if (texture.isReady()) {
  14740. internalTexture = texture.getInternalTexture();
  14741. }
  14742. else if (texture.isCube) {
  14743. internalTexture = this.emptyCubeTexture;
  14744. }
  14745. else if (texture.is3D) {
  14746. internalTexture = this.emptyTexture3D;
  14747. }
  14748. else {
  14749. internalTexture = this.emptyTexture;
  14750. }
  14751. if (!isPartOfTextureArray) {
  14752. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14753. }
  14754. if (this._boundTexturesCache[channel] === internalTexture) {
  14755. this._moveBoundTextureOnTop(internalTexture);
  14756. if (!isPartOfTextureArray) {
  14757. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14758. }
  14759. return false;
  14760. }
  14761. this._activeChannel = channel;
  14762. if (internalTexture && internalTexture.is3D) {
  14763. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14764. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14765. internalTexture._cachedWrapU = texture.wrapU;
  14766. switch (texture.wrapU) {
  14767. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14768. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14769. break;
  14770. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14771. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14772. break;
  14773. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14774. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14775. break;
  14776. }
  14777. }
  14778. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14779. internalTexture._cachedWrapV = texture.wrapV;
  14780. switch (texture.wrapV) {
  14781. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14782. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14783. break;
  14784. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14785. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14786. break;
  14787. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14788. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14789. break;
  14790. }
  14791. }
  14792. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14793. internalTexture._cachedWrapR = texture.wrapR;
  14794. switch (texture.wrapR) {
  14795. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14796. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14797. break;
  14798. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14799. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14800. break;
  14801. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14802. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14803. break;
  14804. }
  14805. }
  14806. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14807. }
  14808. else if (internalTexture && internalTexture.isCube) {
  14809. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14810. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14811. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14812. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14813. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14815. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14816. }
  14817. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14818. }
  14819. else {
  14820. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14821. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14822. internalTexture._cachedWrapU = texture.wrapU;
  14823. switch (texture.wrapU) {
  14824. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14825. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14826. break;
  14827. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14828. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14829. break;
  14830. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14832. break;
  14833. }
  14834. }
  14835. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14836. internalTexture._cachedWrapV = texture.wrapV;
  14837. switch (texture.wrapV) {
  14838. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14840. break;
  14841. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14842. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14843. break;
  14844. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14845. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14846. break;
  14847. }
  14848. }
  14849. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14850. }
  14851. return true;
  14852. };
  14853. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14854. if (channel < 0 || !uniform) {
  14855. return;
  14856. }
  14857. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14858. this._textureUnits = new Int32Array(textures.length);
  14859. }
  14860. for (var i = 0; i < textures.length; i++) {
  14861. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14862. }
  14863. this._gl.uniform1iv(uniform, this._textureUnits);
  14864. for (var index = 0; index < textures.length; index++) {
  14865. this._setTexture(this._textureUnits[index], textures[index], true);
  14866. }
  14867. };
  14868. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14869. var internalTexture = texture.getInternalTexture();
  14870. if (!internalTexture) {
  14871. return;
  14872. }
  14873. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14874. var value = texture.anisotropicFilteringLevel;
  14875. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14876. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14877. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14878. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14879. }
  14880. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14881. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14882. internalTexture._cachedAnisotropicFilteringLevel = value;
  14883. }
  14884. };
  14885. Engine.prototype.readPixels = function (x, y, width, height) {
  14886. var data = new Uint8Array(height * width * 4);
  14887. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14888. return data;
  14889. };
  14890. /**
  14891. * Add an externaly attached data from its key.
  14892. * This method call will fail and return false, if such key already exists.
  14893. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14894. * @param key the unique key that identifies the data
  14895. * @param data the data object to associate to the key for this Engine instance
  14896. * @return true if no such key were already present and the data was added successfully, false otherwise
  14897. */
  14898. Engine.prototype.addExternalData = function (key, data) {
  14899. if (!this._externalData) {
  14900. this._externalData = new BABYLON.StringDictionary();
  14901. }
  14902. return this._externalData.add(key, data);
  14903. };
  14904. /**
  14905. * Get an externaly attached data from its key
  14906. * @param key the unique key that identifies the data
  14907. * @return the associated data, if present (can be null), or undefined if not present
  14908. */
  14909. Engine.prototype.getExternalData = function (key) {
  14910. if (!this._externalData) {
  14911. this._externalData = new BABYLON.StringDictionary();
  14912. }
  14913. return this._externalData.get(key);
  14914. };
  14915. /**
  14916. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14917. * @param key the unique key that identifies the data
  14918. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14919. * @return the associated data, can be null if the factory returned null.
  14920. */
  14921. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14922. if (!this._externalData) {
  14923. this._externalData = new BABYLON.StringDictionary();
  14924. }
  14925. return this._externalData.getOrAddWithFactory(key, factory);
  14926. };
  14927. /**
  14928. * Remove an externaly attached data from the Engine instance
  14929. * @param key the unique key that identifies the data
  14930. * @return true if the data was successfully removed, false if it doesn't exist
  14931. */
  14932. Engine.prototype.removeExternalData = function (key) {
  14933. if (!this._externalData) {
  14934. this._externalData = new BABYLON.StringDictionary();
  14935. }
  14936. return this._externalData.remove(key);
  14937. };
  14938. Engine.prototype.unbindAllAttributes = function () {
  14939. if (this._mustWipeVertexAttributes) {
  14940. this._mustWipeVertexAttributes = false;
  14941. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14942. this._gl.disableVertexAttribArray(i);
  14943. this._vertexAttribArraysEnabled[i] = false;
  14944. this._currentBufferPointers[i].active = false;
  14945. }
  14946. return;
  14947. }
  14948. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14949. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14950. continue;
  14951. }
  14952. this._gl.disableVertexAttribArray(i);
  14953. this._vertexAttribArraysEnabled[i] = false;
  14954. this._currentBufferPointers[i].active = false;
  14955. }
  14956. };
  14957. Engine.prototype.releaseEffects = function () {
  14958. for (var name in this._compiledEffects) {
  14959. this._deleteProgram(this._compiledEffects[name]._program);
  14960. }
  14961. this._compiledEffects = {};
  14962. };
  14963. // Dispose
  14964. Engine.prototype.dispose = function () {
  14965. this.hideLoadingUI();
  14966. this.stopRenderLoop();
  14967. // Release postProcesses
  14968. while (this.postProcesses.length) {
  14969. this.postProcesses[0].dispose();
  14970. }
  14971. // Empty texture
  14972. if (this._emptyTexture) {
  14973. this._releaseTexture(this._emptyTexture);
  14974. this._emptyTexture = null;
  14975. }
  14976. if (this._emptyCubeTexture) {
  14977. this._releaseTexture(this._emptyCubeTexture);
  14978. this._emptyCubeTexture = null;
  14979. }
  14980. // Rescale PP
  14981. if (this._rescalePostProcess) {
  14982. this._rescalePostProcess.dispose();
  14983. }
  14984. // Release scenes
  14985. while (this.scenes.length) {
  14986. this.scenes[0].dispose();
  14987. }
  14988. // Release audio engine
  14989. if (Engine.audioEngine) {
  14990. Engine.audioEngine.dispose();
  14991. }
  14992. // Release effects
  14993. this.releaseEffects();
  14994. // Unbind
  14995. this.unbindAllAttributes();
  14996. this._boundUniforms = [];
  14997. if (this._dummyFramebuffer) {
  14998. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14999. }
  15000. //WebVR
  15001. this.disableVR();
  15002. // Events
  15003. if (BABYLON.Tools.IsWindowObjectExist()) {
  15004. window.removeEventListener("blur", this._onBlur);
  15005. window.removeEventListener("focus", this._onFocus);
  15006. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15007. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15008. if (this._renderingCanvas) {
  15009. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15010. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15011. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15012. if (!this._doNotHandleContextLost) {
  15013. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15014. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15015. }
  15016. }
  15017. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15018. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15019. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15020. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15021. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15022. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15023. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15024. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15025. if (this._onVrDisplayConnect) {
  15026. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15027. if (this._onVrDisplayDisconnect) {
  15028. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15029. }
  15030. if (this._onVrDisplayPresentChange) {
  15031. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15032. }
  15033. this._onVrDisplayConnect = null;
  15034. this._onVrDisplayDisconnect = null;
  15035. }
  15036. }
  15037. // Remove from Instances
  15038. var index = Engine.Instances.indexOf(this);
  15039. if (index >= 0) {
  15040. Engine.Instances.splice(index, 1);
  15041. }
  15042. this._workingCanvas = null;
  15043. this._workingContext = null;
  15044. this._currentBufferPointers = [];
  15045. this._renderingCanvas = null;
  15046. this._currentProgram = null;
  15047. this._bindedRenderFunction = null;
  15048. this.onResizeObservable.clear();
  15049. this.onCanvasBlurObservable.clear();
  15050. this.onCanvasFocusObservable.clear();
  15051. this.onCanvasPointerOutObservable.clear();
  15052. this.onBeginFrameObservable.clear();
  15053. this.onEndFrameObservable.clear();
  15054. BABYLON.Effect.ResetCache();
  15055. // Abort active requests
  15056. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15057. var request = _a[_i];
  15058. request.abort();
  15059. }
  15060. };
  15061. // Loading screen
  15062. Engine.prototype.displayLoadingUI = function () {
  15063. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15064. return;
  15065. }
  15066. var loadingScreen = this.loadingScreen;
  15067. if (loadingScreen) {
  15068. loadingScreen.displayLoadingUI();
  15069. }
  15070. };
  15071. Engine.prototype.hideLoadingUI = function () {
  15072. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15073. return;
  15074. }
  15075. var loadingScreen = this.loadingScreen;
  15076. if (loadingScreen) {
  15077. loadingScreen.hideLoadingUI();
  15078. }
  15079. };
  15080. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15081. get: function () {
  15082. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15083. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15084. return this._loadingScreen;
  15085. },
  15086. set: function (loadingScreen) {
  15087. this._loadingScreen = loadingScreen;
  15088. },
  15089. enumerable: true,
  15090. configurable: true
  15091. });
  15092. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15093. set: function (text) {
  15094. this.loadingScreen.loadingUIText = text;
  15095. },
  15096. enumerable: true,
  15097. configurable: true
  15098. });
  15099. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15100. set: function (color) {
  15101. this.loadingScreen.loadingUIBackgroundColor = color;
  15102. },
  15103. enumerable: true,
  15104. configurable: true
  15105. });
  15106. Engine.prototype.attachContextLostEvent = function (callback) {
  15107. if (this._renderingCanvas) {
  15108. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15109. }
  15110. };
  15111. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15112. if (this._renderingCanvas) {
  15113. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15114. }
  15115. };
  15116. Engine.prototype.getVertexShaderSource = function (program) {
  15117. var shaders = this._gl.getAttachedShaders(program);
  15118. if (!shaders) {
  15119. return null;
  15120. }
  15121. return this._gl.getShaderSource(shaders[0]);
  15122. };
  15123. Engine.prototype.getFragmentShaderSource = function (program) {
  15124. var shaders = this._gl.getAttachedShaders(program);
  15125. if (!shaders) {
  15126. return null;
  15127. }
  15128. return this._gl.getShaderSource(shaders[1]);
  15129. };
  15130. Engine.prototype.getError = function () {
  15131. return this._gl.getError();
  15132. };
  15133. // FPS
  15134. Engine.prototype.getFps = function () {
  15135. return this._fps;
  15136. };
  15137. Engine.prototype.getDeltaTime = function () {
  15138. return this._deltaTime;
  15139. };
  15140. Engine.prototype._measureFps = function () {
  15141. this._performanceMonitor.sampleFrame();
  15142. this._fps = this._performanceMonitor.averageFPS;
  15143. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15144. };
  15145. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15146. if (faceIndex === void 0) { faceIndex = -1; }
  15147. var gl = this._gl;
  15148. if (!this._dummyFramebuffer) {
  15149. var dummy = gl.createFramebuffer();
  15150. if (!dummy) {
  15151. throw new Error("Unable to create dummy framebuffer");
  15152. }
  15153. this._dummyFramebuffer = dummy;
  15154. }
  15155. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15156. if (faceIndex > -1) {
  15157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15158. }
  15159. else {
  15160. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15161. }
  15162. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15163. var buffer;
  15164. switch (readType) {
  15165. case gl.UNSIGNED_BYTE:
  15166. buffer = new Uint8Array(4 * width * height);
  15167. readType = gl.UNSIGNED_BYTE;
  15168. break;
  15169. default:
  15170. buffer = new Float32Array(4 * width * height);
  15171. readType = gl.FLOAT;
  15172. break;
  15173. }
  15174. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15175. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15176. return buffer;
  15177. };
  15178. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15179. if (this._webGLVersion > 1) {
  15180. return this._caps.colorBufferFloat;
  15181. }
  15182. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15183. };
  15184. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15185. if (this._webGLVersion > 1) {
  15186. return this._caps.colorBufferFloat;
  15187. }
  15188. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15189. };
  15190. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15191. Engine.prototype._canRenderToFramebuffer = function (type) {
  15192. var gl = this._gl;
  15193. //clear existing errors
  15194. while (gl.getError() !== gl.NO_ERROR) { }
  15195. var successful = true;
  15196. var texture = gl.createTexture();
  15197. gl.bindTexture(gl.TEXTURE_2D, texture);
  15198. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15201. var fb = gl.createFramebuffer();
  15202. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15203. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15204. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15205. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15206. successful = successful && (gl.getError() === gl.NO_ERROR);
  15207. //try render by clearing frame buffer's color buffer
  15208. if (successful) {
  15209. gl.clear(gl.COLOR_BUFFER_BIT);
  15210. successful = successful && (gl.getError() === gl.NO_ERROR);
  15211. }
  15212. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15213. if (successful) {
  15214. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15215. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15216. var readFormat = gl.RGBA;
  15217. var readType = gl.UNSIGNED_BYTE;
  15218. var buffer = new Uint8Array(4);
  15219. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15220. successful = successful && (gl.getError() === gl.NO_ERROR);
  15221. }
  15222. //clean up
  15223. gl.deleteTexture(texture);
  15224. gl.deleteFramebuffer(fb);
  15225. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15226. //clear accumulated errors
  15227. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15228. return successful;
  15229. };
  15230. Engine.prototype._getWebGLTextureType = function (type) {
  15231. if (type === Engine.TEXTURETYPE_FLOAT) {
  15232. return this._gl.FLOAT;
  15233. }
  15234. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15235. // Add Half Float Constant.
  15236. return this._gl.HALF_FLOAT_OES;
  15237. }
  15238. return this._gl.UNSIGNED_BYTE;
  15239. };
  15240. ;
  15241. Engine.prototype._getInternalFormat = function (format) {
  15242. var internalFormat = this._gl.RGBA;
  15243. switch (format) {
  15244. case Engine.TEXTUREFORMAT_ALPHA:
  15245. internalFormat = this._gl.ALPHA;
  15246. break;
  15247. case Engine.TEXTUREFORMAT_LUMINANCE:
  15248. internalFormat = this._gl.LUMINANCE;
  15249. break;
  15250. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15251. internalFormat = this._gl.LUMINANCE_ALPHA;
  15252. break;
  15253. case Engine.TEXTUREFORMAT_RGB:
  15254. case Engine.TEXTUREFORMAT_RGB32F:
  15255. internalFormat = this._gl.RGB;
  15256. break;
  15257. case Engine.TEXTUREFORMAT_RGBA:
  15258. case Engine.TEXTUREFORMAT_RGBA32F:
  15259. internalFormat = this._gl.RGBA;
  15260. break;
  15261. case Engine.TEXTUREFORMAT_R32F:
  15262. internalFormat = this._gl.RED;
  15263. break;
  15264. case Engine.TEXTUREFORMAT_RG32F:
  15265. internalFormat = this._gl.RG;
  15266. break;
  15267. }
  15268. return internalFormat;
  15269. };
  15270. /** @ignore */
  15271. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15272. if (this._webGLVersion === 1) {
  15273. if (format) {
  15274. switch (format) {
  15275. case Engine.TEXTUREFORMAT_LUMINANCE:
  15276. return this._gl.LUMINANCE;
  15277. }
  15278. }
  15279. return this._gl.RGBA;
  15280. }
  15281. if (type === Engine.TEXTURETYPE_FLOAT) {
  15282. if (format) {
  15283. switch (format) {
  15284. case Engine.TEXTUREFORMAT_R32F:
  15285. return this._gl.R32F;
  15286. case Engine.TEXTUREFORMAT_RG32F:
  15287. return this._gl.RG32F;
  15288. case Engine.TEXTUREFORMAT_RGB32F:
  15289. return this._gl.RGB32F;
  15290. }
  15291. }
  15292. return this._gl.RGBA32F;
  15293. }
  15294. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15295. return this._gl.RGBA16F;
  15296. }
  15297. if (format) {
  15298. switch (format) {
  15299. case Engine.TEXTUREFORMAT_LUMINANCE:
  15300. return this._gl.LUMINANCE;
  15301. }
  15302. }
  15303. return this._gl.RGBA;
  15304. };
  15305. ;
  15306. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15307. if (type === Engine.TEXTURETYPE_FLOAT) {
  15308. return this._gl.RGBA32F;
  15309. }
  15310. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15311. return this._gl.RGBA16F;
  15312. }
  15313. return this._gl.RGBA8;
  15314. };
  15315. ;
  15316. Engine.prototype.createQuery = function () {
  15317. return this._gl.createQuery();
  15318. };
  15319. Engine.prototype.deleteQuery = function (query) {
  15320. this._gl.deleteQuery(query);
  15321. return this;
  15322. };
  15323. Engine.prototype.isQueryResultAvailable = function (query) {
  15324. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15325. };
  15326. Engine.prototype.getQueryResult = function (query) {
  15327. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15328. };
  15329. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15330. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15331. this._gl.beginQuery(glAlgorithm, query);
  15332. return this;
  15333. };
  15334. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15335. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15336. this._gl.endQuery(glAlgorithm);
  15337. return this;
  15338. };
  15339. /* Time queries */
  15340. Engine.prototype._createTimeQuery = function () {
  15341. var timerQuery = this._caps.timerQuery;
  15342. if (timerQuery.createQueryEXT) {
  15343. return timerQuery.createQueryEXT();
  15344. }
  15345. return this.createQuery();
  15346. };
  15347. Engine.prototype._deleteTimeQuery = function (query) {
  15348. var timerQuery = this._caps.timerQuery;
  15349. if (timerQuery.deleteQueryEXT) {
  15350. timerQuery.deleteQueryEXT(query);
  15351. return;
  15352. }
  15353. this.deleteQuery(query);
  15354. };
  15355. Engine.prototype._getTimeQueryResult = function (query) {
  15356. var timerQuery = this._caps.timerQuery;
  15357. if (timerQuery.getQueryObjectEXT) {
  15358. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15359. }
  15360. return this.getQueryResult(query);
  15361. };
  15362. Engine.prototype._getTimeQueryAvailability = function (query) {
  15363. var timerQuery = this._caps.timerQuery;
  15364. if (timerQuery.getQueryObjectEXT) {
  15365. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15366. }
  15367. return this.isQueryResultAvailable(query);
  15368. };
  15369. Engine.prototype.startTimeQuery = function () {
  15370. var timerQuery = this._caps.timerQuery;
  15371. if (!timerQuery) {
  15372. return null;
  15373. }
  15374. var token = new BABYLON._TimeToken();
  15375. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15376. if (this._caps.canUseTimestampForTimerQuery) {
  15377. token._startTimeQuery = this._createTimeQuery();
  15378. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15379. }
  15380. else {
  15381. if (this._currentNonTimestampToken) {
  15382. return this._currentNonTimestampToken;
  15383. }
  15384. token._timeElapsedQuery = this._createTimeQuery();
  15385. if (timerQuery.beginQueryEXT) {
  15386. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15387. }
  15388. else {
  15389. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15390. }
  15391. this._currentNonTimestampToken = token;
  15392. }
  15393. return token;
  15394. };
  15395. Engine.prototype.endTimeQuery = function (token) {
  15396. var timerQuery = this._caps.timerQuery;
  15397. if (!timerQuery || !token) {
  15398. return -1;
  15399. }
  15400. if (this._caps.canUseTimestampForTimerQuery) {
  15401. if (!token._startTimeQuery) {
  15402. return -1;
  15403. }
  15404. if (!token._endTimeQuery) {
  15405. token._endTimeQuery = this._createTimeQuery();
  15406. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15407. }
  15408. }
  15409. else if (!token._timeElapsedQueryEnded) {
  15410. if (!token._timeElapsedQuery) {
  15411. return -1;
  15412. }
  15413. if (timerQuery.endQueryEXT) {
  15414. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15415. }
  15416. else {
  15417. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15418. }
  15419. token._timeElapsedQueryEnded = true;
  15420. }
  15421. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15422. var available = false;
  15423. if (token._endTimeQuery) {
  15424. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15425. }
  15426. else if (token._timeElapsedQuery) {
  15427. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15428. }
  15429. if (available && !disjoint) {
  15430. var result = 0;
  15431. if (this._caps.canUseTimestampForTimerQuery) {
  15432. if (!token._startTimeQuery || !token._endTimeQuery) {
  15433. return -1;
  15434. }
  15435. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15436. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15437. result = timeEnd - timeStart;
  15438. this._deleteTimeQuery(token._startTimeQuery);
  15439. this._deleteTimeQuery(token._endTimeQuery);
  15440. token._startTimeQuery = null;
  15441. token._endTimeQuery = null;
  15442. }
  15443. else {
  15444. if (!token._timeElapsedQuery) {
  15445. return -1;
  15446. }
  15447. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15448. this._deleteTimeQuery(token._timeElapsedQuery);
  15449. token._timeElapsedQuery = null;
  15450. token._timeElapsedQueryEnded = false;
  15451. this._currentNonTimestampToken = null;
  15452. }
  15453. return result;
  15454. }
  15455. return -1;
  15456. };
  15457. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15458. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15459. };
  15460. // Transform feedback
  15461. Engine.prototype.createTransformFeedback = function () {
  15462. return this._gl.createTransformFeedback();
  15463. };
  15464. Engine.prototype.deleteTransformFeedback = function (value) {
  15465. this._gl.deleteTransformFeedback(value);
  15466. };
  15467. Engine.prototype.bindTransformFeedback = function (value) {
  15468. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15469. };
  15470. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15471. if (usePoints === void 0) { usePoints = true; }
  15472. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15473. };
  15474. Engine.prototype.endTransformFeedback = function () {
  15475. this._gl.endTransformFeedback();
  15476. };
  15477. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15478. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15479. };
  15480. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15481. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15482. };
  15483. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15484. var _this = this;
  15485. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15486. this._activeRequests.push(request);
  15487. request.onCompleteObservable.add(function (request) {
  15488. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15489. });
  15490. return request;
  15491. };
  15492. /** @ignore */
  15493. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15494. var _this = this;
  15495. return new Promise(function (resolve, reject) {
  15496. _this._loadFile(url, function (data) {
  15497. resolve(data);
  15498. }, undefined, database, useArrayBuffer, function (request, exception) {
  15499. reject(exception);
  15500. });
  15501. });
  15502. };
  15503. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15504. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15505. var onload = function (data) {
  15506. loadedFiles[index] = data;
  15507. loadedFiles._internalCount++;
  15508. if (loadedFiles._internalCount === 6) {
  15509. onfinish(loadedFiles);
  15510. }
  15511. };
  15512. var onerror = function (request, exception) {
  15513. if (onErrorCallBack && request) {
  15514. onErrorCallBack(request.status + " " + request.statusText, exception);
  15515. }
  15516. };
  15517. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15518. };
  15519. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15520. if (onError === void 0) { onError = null; }
  15521. var loadedFiles = [];
  15522. loadedFiles._internalCount = 0;
  15523. for (var index = 0; index < 6; index++) {
  15524. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15525. }
  15526. };
  15527. // Statics
  15528. Engine.isSupported = function () {
  15529. try {
  15530. var tempcanvas = document.createElement("canvas");
  15531. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15532. return gl != null && !!window.WebGLRenderingContext;
  15533. }
  15534. catch (e) {
  15535. return false;
  15536. }
  15537. };
  15538. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15539. Engine.ExceptionList = [
  15540. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15541. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15542. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15543. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15544. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15545. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15546. ];
  15547. Engine.Instances = new Array();
  15548. // Const statics
  15549. Engine._ALPHA_DISABLE = 0;
  15550. Engine._ALPHA_ADD = 1;
  15551. Engine._ALPHA_COMBINE = 2;
  15552. Engine._ALPHA_SUBTRACT = 3;
  15553. Engine._ALPHA_MULTIPLY = 4;
  15554. Engine._ALPHA_MAXIMIZED = 5;
  15555. Engine._ALPHA_ONEONE = 6;
  15556. Engine._ALPHA_PREMULTIPLIED = 7;
  15557. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15558. Engine._ALPHA_INTERPOLATE = 9;
  15559. Engine._ALPHA_SCREENMODE = 10;
  15560. Engine._DELAYLOADSTATE_NONE = 0;
  15561. Engine._DELAYLOADSTATE_LOADED = 1;
  15562. Engine._DELAYLOADSTATE_LOADING = 2;
  15563. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15564. Engine._TEXTUREFORMAT_ALPHA = 0;
  15565. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15566. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15567. Engine._TEXTUREFORMAT_RGB = 4;
  15568. Engine._TEXTUREFORMAT_RGBA = 5;
  15569. Engine._TEXTUREFORMAT_R32F = 6;
  15570. Engine._TEXTUREFORMAT_RG32F = 7;
  15571. Engine._TEXTUREFORMAT_RGB32F = 8;
  15572. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15573. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15574. Engine._TEXTURETYPE_FLOAT = 1;
  15575. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15576. // Depht or Stencil test Constants.
  15577. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15578. 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.
  15579. 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.
  15580. 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.
  15581. 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.
  15582. 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.
  15583. 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.
  15584. 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.
  15585. // Stencil Actions Constants.
  15586. Engine._KEEP = 0x1E00;
  15587. Engine._REPLACE = 0x1E01;
  15588. Engine._INCR = 0x1E02;
  15589. Engine._DECR = 0x1E03;
  15590. Engine._INVERT = 0x150A;
  15591. Engine._INCR_WRAP = 0x8507;
  15592. Engine._DECR_WRAP = 0x8508;
  15593. // Texture rescaling mode
  15594. Engine._SCALEMODE_FLOOR = 1;
  15595. Engine._SCALEMODE_NEAREST = 2;
  15596. Engine._SCALEMODE_CEILING = 3;
  15597. // Updatable statics so stick with vars here
  15598. Engine.CollisionsEpsilon = 0.001;
  15599. Engine.CodeRepository = "src/";
  15600. Engine.ShadersRepository = "src/Shaders/";
  15601. return Engine;
  15602. }());
  15603. BABYLON.Engine = Engine;
  15604. })(BABYLON || (BABYLON = {}));
  15605. //# sourceMappingURL=babylon.engine.js.map
  15606. "use strict";
  15607. var BABYLON;
  15608. (function (BABYLON) {
  15609. /**
  15610. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15611. */
  15612. var Node = /** @class */ (function () {
  15613. /**
  15614. * Creates a new Node
  15615. * @param {string} name - the name and id to be given to this node
  15616. * @param {BABYLON.Scene} the scene this node will be added to
  15617. */
  15618. function Node(name, scene) {
  15619. if (scene === void 0) { scene = null; }
  15620. /**
  15621. * Gets or sets a string used to store user defined state for the node
  15622. */
  15623. this.state = "";
  15624. /**
  15625. * Gets or sets an object used to store user defined information for the node
  15626. */
  15627. this.metadata = null;
  15628. /**
  15629. * Gets or sets a boolean used to define if the node must be serialized
  15630. */
  15631. this.doNotSerialize = false;
  15632. /** @ignore */
  15633. this._isDisposed = false;
  15634. /**
  15635. * Gets a list of Animations associated with the node
  15636. */
  15637. this.animations = new Array();
  15638. this._ranges = {};
  15639. this._isEnabled = true;
  15640. this._isReady = true;
  15641. /** @ignore */
  15642. this._currentRenderId = -1;
  15643. this._parentRenderId = -1;
  15644. this._childRenderId = -1;
  15645. this._animationPropertiesOverride = null;
  15646. /**
  15647. * An event triggered when the mesh is disposed
  15648. */
  15649. this.onDisposeObservable = new BABYLON.Observable();
  15650. // Behaviors
  15651. this._behaviors = new Array();
  15652. this.name = name;
  15653. this.id = name;
  15654. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15655. this.uniqueId = this._scene.getUniqueId();
  15656. this._initCache();
  15657. }
  15658. /**
  15659. * Gets a boolean indicating if the node has been disposed
  15660. * @returns true if the node was disposed
  15661. */
  15662. Node.prototype.isDisposed = function () {
  15663. return this._isDisposed;
  15664. };
  15665. Object.defineProperty(Node.prototype, "parent", {
  15666. get: function () {
  15667. return this._parentNode;
  15668. },
  15669. /**
  15670. * Gets or sets the parent of the node
  15671. */
  15672. set: function (parent) {
  15673. if (this._parentNode === parent) {
  15674. return;
  15675. }
  15676. // Remove self from list of children of parent
  15677. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15678. var index = this._parentNode._children.indexOf(this);
  15679. if (index !== -1) {
  15680. this._parentNode._children.splice(index, 1);
  15681. }
  15682. }
  15683. // Store new parent
  15684. this._parentNode = parent;
  15685. // Add as child to new parent
  15686. if (this._parentNode) {
  15687. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15688. this._parentNode._children = new Array();
  15689. }
  15690. this._parentNode._children.push(this);
  15691. }
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15697. /**
  15698. * Gets or sets the animation properties override
  15699. */
  15700. get: function () {
  15701. return this._animationPropertiesOverride;
  15702. },
  15703. set: function (value) {
  15704. this._animationPropertiesOverride = value;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. /**
  15710. * Gets a string idenfifying the name of the class
  15711. * @returns "Node" string
  15712. */
  15713. Node.prototype.getClassName = function () {
  15714. return "Node";
  15715. };
  15716. Object.defineProperty(Node.prototype, "onDispose", {
  15717. /**
  15718. * Sets a callback that will be raised when the node will be disposed
  15719. */
  15720. set: function (callback) {
  15721. if (this._onDisposeObserver) {
  15722. this.onDisposeObservable.remove(this._onDisposeObserver);
  15723. }
  15724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. /**
  15730. * Gets the scene of the node
  15731. * @returns a {BABYLON.Scene}
  15732. */
  15733. Node.prototype.getScene = function () {
  15734. return this._scene;
  15735. };
  15736. /**
  15737. * Gets the engine of the node
  15738. * @returns a {BABYLON.Engine}
  15739. */
  15740. Node.prototype.getEngine = function () {
  15741. return this._scene.getEngine();
  15742. };
  15743. /**
  15744. * Attach a behavior to the node
  15745. * @see http://doc.babylonjs.com/features/behaviour
  15746. * @param behavior defines the behavior to attach
  15747. * @returns the current Node
  15748. */
  15749. Node.prototype.addBehavior = function (behavior) {
  15750. var _this = this;
  15751. var index = this._behaviors.indexOf(behavior);
  15752. if (index !== -1) {
  15753. return this;
  15754. }
  15755. behavior.init();
  15756. if (this._scene.isLoading) {
  15757. // We defer the attach when the scene will be loaded
  15758. var observer = this._scene.onDataLoadedObservable.add(function () {
  15759. behavior.attach(_this);
  15760. setTimeout(function () {
  15761. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15762. _this._scene.onDataLoadedObservable.remove(observer);
  15763. }, 0);
  15764. });
  15765. }
  15766. else {
  15767. behavior.attach(this);
  15768. }
  15769. this._behaviors.push(behavior);
  15770. return this;
  15771. };
  15772. /**
  15773. * Remove an attached behavior
  15774. * @see http://doc.babylonjs.com/features/behaviour
  15775. * @param behavior defines the behavior to attach
  15776. * @returns the current Node
  15777. */
  15778. Node.prototype.removeBehavior = function (behavior) {
  15779. var index = this._behaviors.indexOf(behavior);
  15780. if (index === -1) {
  15781. return this;
  15782. }
  15783. this._behaviors[index].detach();
  15784. this._behaviors.splice(index, 1);
  15785. return this;
  15786. };
  15787. Object.defineProperty(Node.prototype, "behaviors", {
  15788. /**
  15789. * Gets the list of attached behaviors
  15790. * @see http://doc.babylonjs.com/features/behaviour
  15791. */
  15792. get: function () {
  15793. return this._behaviors;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. /**
  15799. * Gets an attached behavior by name
  15800. * @param name defines the name of the behavior to look for
  15801. * @see http://doc.babylonjs.com/features/behaviour
  15802. * @returns null if behavior was not found else the requested behavior
  15803. */
  15804. Node.prototype.getBehaviorByName = function (name) {
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. if (behavior.name === name) {
  15808. return behavior;
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. /**
  15814. * Returns the world matrix of the node
  15815. * @returns a matrix containing the node's world matrix
  15816. */
  15817. Node.prototype.getWorldMatrix = function () {
  15818. return BABYLON.Matrix.Identity();
  15819. };
  15820. // override it in derived class if you add new variables to the cache
  15821. // and call the parent class method
  15822. /** @ignore */
  15823. Node.prototype._initCache = function () {
  15824. this._cache = {};
  15825. this._cache.parent = undefined;
  15826. };
  15827. /** @ignore */
  15828. Node.prototype.updateCache = function (force) {
  15829. if (!force && this.isSynchronized())
  15830. return;
  15831. this._cache.parent = this.parent;
  15832. this._updateCache();
  15833. };
  15834. // override it in derived class if you add new variables to the cache
  15835. // and call the parent class method if !ignoreParentClass
  15836. /** @ignore */
  15837. Node.prototype._updateCache = function (ignoreParentClass) {
  15838. };
  15839. // override it in derived class if you add new variables to the cache
  15840. /** @ignore */
  15841. Node.prototype._isSynchronized = function () {
  15842. return true;
  15843. };
  15844. /** @ignore */
  15845. Node.prototype._markSyncedWithParent = function () {
  15846. if (this.parent) {
  15847. this._parentRenderId = this.parent._childRenderId;
  15848. }
  15849. };
  15850. /** @ignore */
  15851. Node.prototype.isSynchronizedWithParent = function () {
  15852. if (!this.parent) {
  15853. return true;
  15854. }
  15855. if (this._parentRenderId !== this.parent._childRenderId) {
  15856. return false;
  15857. }
  15858. return this.parent.isSynchronized();
  15859. };
  15860. /** @ignore */
  15861. Node.prototype.isSynchronized = function (updateCache) {
  15862. var check = this.hasNewParent();
  15863. check = check || !this.isSynchronizedWithParent();
  15864. check = check || !this._isSynchronized();
  15865. if (updateCache)
  15866. this.updateCache(true);
  15867. return !check;
  15868. };
  15869. /** @ignore */
  15870. Node.prototype.hasNewParent = function (update) {
  15871. if (this._cache.parent === this.parent)
  15872. return false;
  15873. if (update)
  15874. this._cache.parent = this.parent;
  15875. return true;
  15876. };
  15877. /**
  15878. * Is this node ready to be used/rendered
  15879. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15880. * @return true if the node is ready
  15881. */
  15882. Node.prototype.isReady = function (completeCheck) {
  15883. if (completeCheck === void 0) { completeCheck = false; }
  15884. return this._isReady;
  15885. };
  15886. /**
  15887. * Is this node enabled?
  15888. * 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
  15889. * @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
  15890. * @return whether this node (and its parent) is enabled
  15891. */
  15892. Node.prototype.isEnabled = function (checkAncestors) {
  15893. if (checkAncestors === void 0) { checkAncestors = true; }
  15894. if (checkAncestors === false) {
  15895. return this._isEnabled;
  15896. }
  15897. if (this._isEnabled === false) {
  15898. return false;
  15899. }
  15900. if (this.parent !== undefined && this.parent !== null) {
  15901. return this.parent.isEnabled(checkAncestors);
  15902. }
  15903. return true;
  15904. };
  15905. /**
  15906. * Set the enabled state of this node
  15907. * @param value defines the new enabled state
  15908. */
  15909. Node.prototype.setEnabled = function (value) {
  15910. this._isEnabled = value;
  15911. };
  15912. /**
  15913. * Is this node a descendant of the given node?
  15914. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15915. * @param ancestor defines the parent node to inspect
  15916. * @returns a boolean indicating if this node is a descendant of the given node
  15917. */
  15918. Node.prototype.isDescendantOf = function (ancestor) {
  15919. if (this.parent) {
  15920. if (this.parent === ancestor) {
  15921. return true;
  15922. }
  15923. return this.parent.isDescendantOf(ancestor);
  15924. }
  15925. return false;
  15926. };
  15927. /** @ignore */
  15928. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15929. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15930. if (!this._children) {
  15931. return;
  15932. }
  15933. for (var index = 0; index < this._children.length; index++) {
  15934. var item = this._children[index];
  15935. if (!predicate || predicate(item)) {
  15936. results.push(item);
  15937. }
  15938. if (!directDescendantsOnly) {
  15939. item._getDescendants(results, false, predicate);
  15940. }
  15941. }
  15942. };
  15943. /**
  15944. * Will return all nodes that have this node as ascendant
  15945. * @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
  15946. * @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
  15947. * @return all children nodes of all types
  15948. */
  15949. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15950. var results = new Array();
  15951. this._getDescendants(results, directDescendantsOnly, predicate);
  15952. return results;
  15953. };
  15954. /**
  15955. * Get all child-meshes of this node
  15956. * @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
  15957. * @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
  15958. * @returns an array of {BABYLON.AbstractMesh}
  15959. */
  15960. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15961. var results = [];
  15962. this._getDescendants(results, directDescendantsOnly, function (node) {
  15963. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15964. });
  15965. return results;
  15966. };
  15967. /**
  15968. * Get all child-transformNodes of this node
  15969. * @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
  15970. * @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
  15971. * @returns an array of {BABYLON.TransformNode}
  15972. */
  15973. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15974. var results = [];
  15975. this._getDescendants(results, directDescendantsOnly, function (node) {
  15976. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15977. });
  15978. return results;
  15979. };
  15980. /**
  15981. * Get all direct children of this node
  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.Node}
  15984. */
  15985. Node.prototype.getChildren = function (predicate) {
  15986. return this.getDescendants(true, predicate);
  15987. };
  15988. /** @ignore */
  15989. Node.prototype._setReady = function (state) {
  15990. if (state === this._isReady) {
  15991. return;
  15992. }
  15993. if (!state) {
  15994. this._isReady = false;
  15995. return;
  15996. }
  15997. if (this.onReady) {
  15998. this.onReady(this);
  15999. }
  16000. this._isReady = true;
  16001. };
  16002. /**
  16003. * Get an animation by name
  16004. * @param name defines the name of the animation to look for
  16005. * @returns null if not found else the requested animation
  16006. */
  16007. Node.prototype.getAnimationByName = function (name) {
  16008. for (var i = 0; i < this.animations.length; i++) {
  16009. var animation = this.animations[i];
  16010. if (animation.name === name) {
  16011. return animation;
  16012. }
  16013. }
  16014. return null;
  16015. };
  16016. /**
  16017. * Creates an animation range for this node
  16018. * @param name defines the name of the range
  16019. * @param from defines the starting key
  16020. * @param to defines the end key
  16021. */
  16022. Node.prototype.createAnimationRange = function (name, from, to) {
  16023. // check name not already in use
  16024. if (!this._ranges[name]) {
  16025. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16026. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16027. if (this.animations[i]) {
  16028. this.animations[i].createRange(name, from, to);
  16029. }
  16030. }
  16031. }
  16032. };
  16033. /**
  16034. * Delete a specific animation range
  16035. * @param name defines the name of the range to delete
  16036. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16037. */
  16038. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16039. if (deleteFrames === void 0) { deleteFrames = true; }
  16040. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16041. if (this.animations[i]) {
  16042. this.animations[i].deleteRange(name, deleteFrames);
  16043. }
  16044. }
  16045. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16046. };
  16047. /**
  16048. * Get an animation range by name
  16049. * @param name defines the name of the animation range to look for
  16050. * @returns null if not found else the requested animation range
  16051. */
  16052. Node.prototype.getAnimationRange = function (name) {
  16053. return this._ranges[name];
  16054. };
  16055. /**
  16056. * Will start the animation sequence
  16057. * @param name defines the range frames for animation sequence
  16058. * @param loop defines if the animation should loop (false by default)
  16059. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16060. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16061. * @returns the object created for this animation. If range does not exist, it will return null
  16062. */
  16063. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16064. var range = this.getAnimationRange(name);
  16065. if (!range) {
  16066. return null;
  16067. }
  16068. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16069. };
  16070. /**
  16071. * Serialize animation ranges into a JSON compatible object
  16072. * @returns serialization object
  16073. */
  16074. Node.prototype.serializeAnimationRanges = function () {
  16075. var serializationRanges = [];
  16076. for (var name in this._ranges) {
  16077. var localRange = this._ranges[name];
  16078. if (!localRange) {
  16079. continue;
  16080. }
  16081. var range = {};
  16082. range.name = name;
  16083. range.from = localRange.from;
  16084. range.to = localRange.to;
  16085. serializationRanges.push(range);
  16086. }
  16087. return serializationRanges;
  16088. };
  16089. /**
  16090. * Computes the world matrix of the node
  16091. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16092. * @returns the world matrix
  16093. */
  16094. Node.prototype.computeWorldMatrix = function (force) {
  16095. return BABYLON.Matrix.Identity();
  16096. };
  16097. /**
  16098. * Releases resources associated with this node.
  16099. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16100. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16101. */
  16102. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16103. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16104. if (!doNotRecurse) {
  16105. var nodes = this.getDescendants(true);
  16106. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16107. var node = nodes_1[_i];
  16108. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16109. }
  16110. }
  16111. else {
  16112. var transformNodes = this.getChildTransformNodes(true);
  16113. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16114. var transformNode = transformNodes_1[_a];
  16115. transformNode.parent = null;
  16116. transformNode.computeWorldMatrix(true);
  16117. }
  16118. }
  16119. this.parent = null;
  16120. // Callback
  16121. this.onDisposeObservable.notifyObservers(this);
  16122. this.onDisposeObservable.clear();
  16123. // Behaviors
  16124. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16125. var behavior = _c[_b];
  16126. behavior.detach();
  16127. }
  16128. this._behaviors = [];
  16129. this._isDisposed = true;
  16130. };
  16131. /**
  16132. * Parse animation range data from a serialization object and store them into a given node
  16133. * @param node defines where to store the animation ranges
  16134. * @param parsedNode defines the serialization object to read data from
  16135. * @param scene defines the hosting scene
  16136. */
  16137. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16138. if (parsedNode.ranges) {
  16139. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16140. var data = parsedNode.ranges[index];
  16141. node.createAnimationRange(data.name, data.from, data.to);
  16142. }
  16143. }
  16144. };
  16145. __decorate([
  16146. BABYLON.serialize()
  16147. ], Node.prototype, "name", void 0);
  16148. __decorate([
  16149. BABYLON.serialize()
  16150. ], Node.prototype, "id", void 0);
  16151. __decorate([
  16152. BABYLON.serialize()
  16153. ], Node.prototype, "uniqueId", void 0);
  16154. __decorate([
  16155. BABYLON.serialize()
  16156. ], Node.prototype, "state", void 0);
  16157. __decorate([
  16158. BABYLON.serialize()
  16159. ], Node.prototype, "metadata", void 0);
  16160. return Node;
  16161. }());
  16162. BABYLON.Node = Node;
  16163. })(BABYLON || (BABYLON = {}));
  16164. //# sourceMappingURL=babylon.node.js.map
  16165. "use strict";
  16166. var BABYLON;
  16167. (function (BABYLON) {
  16168. var BoundingSphere = /** @class */ (function () {
  16169. function BoundingSphere(minimum, maximum) {
  16170. this.minimum = minimum;
  16171. this.maximum = maximum;
  16172. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16173. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16174. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16175. this.radius = distance * 0.5;
  16176. this.centerWorld = BABYLON.Vector3.Zero();
  16177. this._update(BABYLON.Matrix.Identity());
  16178. }
  16179. // Methods
  16180. BoundingSphere.prototype._update = function (world) {
  16181. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16182. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16183. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16184. };
  16185. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16186. for (var i = 0; i < 6; i++) {
  16187. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16188. return false;
  16189. }
  16190. return true;
  16191. };
  16192. BoundingSphere.prototype.intersectsPoint = function (point) {
  16193. var x = this.centerWorld.x - point.x;
  16194. var y = this.centerWorld.y - point.y;
  16195. var z = this.centerWorld.z - point.z;
  16196. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16197. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16198. return false;
  16199. return true;
  16200. };
  16201. // Statics
  16202. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16203. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16204. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16205. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16206. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16207. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16208. return false;
  16209. return true;
  16210. };
  16211. return BoundingSphere;
  16212. }());
  16213. BABYLON.BoundingSphere = BoundingSphere;
  16214. })(BABYLON || (BABYLON = {}));
  16215. //# sourceMappingURL=babylon.boundingSphere.js.map
  16216. "use strict";
  16217. var BABYLON;
  16218. (function (BABYLON) {
  16219. var BoundingBox = /** @class */ (function () {
  16220. function BoundingBox(minimum, maximum) {
  16221. this.minimum = minimum;
  16222. this.maximum = maximum;
  16223. this.vectors = new Array();
  16224. this.vectorsWorld = new Array();
  16225. // Bounding vectors
  16226. this.vectors.push(this.minimum.clone());
  16227. this.vectors.push(this.maximum.clone());
  16228. this.vectors.push(this.minimum.clone());
  16229. this.vectors[2].x = this.maximum.x;
  16230. this.vectors.push(this.minimum.clone());
  16231. this.vectors[3].y = this.maximum.y;
  16232. this.vectors.push(this.minimum.clone());
  16233. this.vectors[4].z = this.maximum.z;
  16234. this.vectors.push(this.maximum.clone());
  16235. this.vectors[5].z = this.minimum.z;
  16236. this.vectors.push(this.maximum.clone());
  16237. this.vectors[6].x = this.minimum.x;
  16238. this.vectors.push(this.maximum.clone());
  16239. this.vectors[7].y = this.minimum.y;
  16240. // OBB
  16241. this.center = this.maximum.add(this.minimum).scale(0.5);
  16242. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16243. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16244. // World
  16245. for (var index = 0; index < this.vectors.length; index++) {
  16246. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16247. }
  16248. this.minimumWorld = BABYLON.Vector3.Zero();
  16249. this.maximumWorld = BABYLON.Vector3.Zero();
  16250. this.centerWorld = BABYLON.Vector3.Zero();
  16251. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16252. this._update(BABYLON.Matrix.Identity());
  16253. }
  16254. // Methods
  16255. BoundingBox.prototype.getWorldMatrix = function () {
  16256. return this._worldMatrix;
  16257. };
  16258. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16259. this._worldMatrix.copyFrom(matrix);
  16260. return this;
  16261. };
  16262. BoundingBox.prototype._update = function (world) {
  16263. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16264. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16265. for (var index = 0; index < this.vectors.length; index++) {
  16266. var v = this.vectorsWorld[index];
  16267. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16268. if (v.x < this.minimumWorld.x)
  16269. this.minimumWorld.x = v.x;
  16270. if (v.y < this.minimumWorld.y)
  16271. this.minimumWorld.y = v.y;
  16272. if (v.z < this.minimumWorld.z)
  16273. this.minimumWorld.z = v.z;
  16274. if (v.x > this.maximumWorld.x)
  16275. this.maximumWorld.x = v.x;
  16276. if (v.y > this.maximumWorld.y)
  16277. this.maximumWorld.y = v.y;
  16278. if (v.z > this.maximumWorld.z)
  16279. this.maximumWorld.z = v.z;
  16280. }
  16281. // Extend
  16282. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16283. this.extendSizeWorld.scaleInPlace(0.5);
  16284. // OBB
  16285. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16286. this.centerWorld.scaleInPlace(0.5);
  16287. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16288. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16289. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16290. this._worldMatrix = world;
  16291. };
  16292. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16293. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16294. };
  16295. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16296. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16297. };
  16298. BoundingBox.prototype.intersectsPoint = function (point) {
  16299. var delta = -BABYLON.Epsilon;
  16300. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16301. return false;
  16302. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16303. return false;
  16304. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16305. return false;
  16306. return true;
  16307. };
  16308. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16309. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16310. };
  16311. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16312. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16313. return false;
  16314. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16315. return false;
  16316. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16317. return false;
  16318. return true;
  16319. };
  16320. // Statics
  16321. BoundingBox.Intersects = function (box0, box1) {
  16322. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16323. return false;
  16324. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16325. return false;
  16326. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16327. return false;
  16328. return true;
  16329. };
  16330. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16331. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16332. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16333. return (num <= (sphereRadius * sphereRadius));
  16334. };
  16335. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16336. for (var p = 0; p < 6; p++) {
  16337. for (var i = 0; i < 8; i++) {
  16338. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16339. return false;
  16340. }
  16341. }
  16342. }
  16343. return true;
  16344. };
  16345. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16346. for (var p = 0; p < 6; p++) {
  16347. var inCount = 8;
  16348. for (var i = 0; i < 8; i++) {
  16349. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16350. --inCount;
  16351. }
  16352. else {
  16353. break;
  16354. }
  16355. }
  16356. if (inCount === 0)
  16357. return false;
  16358. }
  16359. return true;
  16360. };
  16361. return BoundingBox;
  16362. }());
  16363. BABYLON.BoundingBox = BoundingBox;
  16364. })(BABYLON || (BABYLON = {}));
  16365. //# sourceMappingURL=babylon.boundingBox.js.map
  16366. "use strict";
  16367. var BABYLON;
  16368. (function (BABYLON) {
  16369. var computeBoxExtents = function (axis, box) {
  16370. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16371. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16372. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16373. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16374. var r = r0 + r1 + r2;
  16375. return {
  16376. min: p - r,
  16377. max: p + r
  16378. };
  16379. };
  16380. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16381. var axisOverlap = function (axis, box0, box1) {
  16382. var result0 = computeBoxExtents(axis, box0);
  16383. var result1 = computeBoxExtents(axis, box1);
  16384. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16385. };
  16386. var BoundingInfo = /** @class */ (function () {
  16387. function BoundingInfo(minimum, maximum) {
  16388. this.minimum = minimum;
  16389. this.maximum = maximum;
  16390. this._isLocked = false;
  16391. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16392. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16393. }
  16394. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16395. get: function () {
  16396. return this._isLocked;
  16397. },
  16398. set: function (value) {
  16399. this._isLocked = value;
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. // Methods
  16405. BoundingInfo.prototype.update = function (world) {
  16406. if (this._isLocked) {
  16407. return;
  16408. }
  16409. this.boundingBox._update(world);
  16410. this.boundingSphere._update(world);
  16411. };
  16412. /**
  16413. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16414. * @param center New center of the bounding info
  16415. * @param extend New extend of the bounding info
  16416. */
  16417. BoundingInfo.prototype.centerOn = function (center, extend) {
  16418. this.minimum = center.subtract(extend);
  16419. this.maximum = center.add(extend);
  16420. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16421. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16422. return this;
  16423. };
  16424. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16425. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16426. return false;
  16427. return this.boundingBox.isInFrustum(frustumPlanes);
  16428. };
  16429. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16430. /**
  16431. * Gets the world distance between the min and max points of the bounding box
  16432. */
  16433. get: function () {
  16434. var boundingBox = this.boundingBox;
  16435. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16436. return size.length();
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16442. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16443. };
  16444. BoundingInfo.prototype._checkCollision = function (collider) {
  16445. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16446. };
  16447. BoundingInfo.prototype.intersectsPoint = function (point) {
  16448. if (!this.boundingSphere.centerWorld) {
  16449. return false;
  16450. }
  16451. if (!this.boundingSphere.intersectsPoint(point)) {
  16452. return false;
  16453. }
  16454. if (!this.boundingBox.intersectsPoint(point)) {
  16455. return false;
  16456. }
  16457. return true;
  16458. };
  16459. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16460. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16461. return false;
  16462. }
  16463. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16464. return false;
  16465. }
  16466. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16467. return false;
  16468. }
  16469. if (!precise) {
  16470. return true;
  16471. }
  16472. var box0 = this.boundingBox;
  16473. var box1 = boundingInfo.boundingBox;
  16474. if (!axisOverlap(box0.directions[0], box0, box1))
  16475. return false;
  16476. if (!axisOverlap(box0.directions[1], box0, box1))
  16477. return false;
  16478. if (!axisOverlap(box0.directions[2], box0, box1))
  16479. return false;
  16480. if (!axisOverlap(box1.directions[0], box0, box1))
  16481. return false;
  16482. if (!axisOverlap(box1.directions[1], box0, box1))
  16483. return false;
  16484. if (!axisOverlap(box1.directions[2], box0, box1))
  16485. return false;
  16486. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16487. return false;
  16488. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16489. return false;
  16490. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16491. return false;
  16492. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16493. return false;
  16494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16495. return false;
  16496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16497. return false;
  16498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16499. return false;
  16500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16501. return false;
  16502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16503. return false;
  16504. return true;
  16505. };
  16506. return BoundingInfo;
  16507. }());
  16508. BABYLON.BoundingInfo = BoundingInfo;
  16509. })(BABYLON || (BABYLON = {}));
  16510. //# sourceMappingURL=babylon.boundingInfo.js.map
  16511. "use strict";
  16512. var BABYLON;
  16513. (function (BABYLON) {
  16514. var TransformNode = /** @class */ (function (_super) {
  16515. __extends(TransformNode, _super);
  16516. function TransformNode(name, scene, isPure) {
  16517. if (scene === void 0) { scene = null; }
  16518. if (isPure === void 0) { isPure = true; }
  16519. var _this = _super.call(this, name, scene) || this;
  16520. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16521. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16522. _this._up = new BABYLON.Vector3(0, 1, 0);
  16523. _this._right = new BABYLON.Vector3(1, 0, 0);
  16524. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16525. // Properties
  16526. _this._rotation = BABYLON.Vector3.Zero();
  16527. _this._scaling = BABYLON.Vector3.One();
  16528. _this._isDirty = false;
  16529. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16530. _this.scalingDeterminant = 1;
  16531. _this.infiniteDistance = false;
  16532. _this.position = BABYLON.Vector3.Zero();
  16533. _this._localWorld = BABYLON.Matrix.Zero();
  16534. _this._worldMatrix = BABYLON.Matrix.Zero();
  16535. _this._worldMatrixDeterminant = 0;
  16536. _this._absolutePosition = BABYLON.Vector3.Zero();
  16537. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16538. _this._postMultiplyPivotMatrix = false;
  16539. _this._isWorldMatrixFrozen = false;
  16540. /**
  16541. * An event triggered after the world matrix is updated
  16542. */
  16543. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16544. _this._nonUniformScaling = false;
  16545. if (isPure) {
  16546. _this.getScene().addTransformNode(_this);
  16547. }
  16548. return _this;
  16549. }
  16550. /**
  16551. * Gets a string idenfifying the name of the class
  16552. * @returns "TransformNode" string
  16553. */
  16554. TransformNode.prototype.getClassName = function () {
  16555. return "TransformNode";
  16556. };
  16557. Object.defineProperty(TransformNode.prototype, "rotation", {
  16558. /**
  16559. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16560. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16561. * Default : (0.0, 0.0, 0.0)
  16562. */
  16563. get: function () {
  16564. return this._rotation;
  16565. },
  16566. set: function (newRotation) {
  16567. this._rotation = newRotation;
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. Object.defineProperty(TransformNode.prototype, "scaling", {
  16573. /**
  16574. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16575. * Default : (1.0, 1.0, 1.0)
  16576. */
  16577. get: function () {
  16578. return this._scaling;
  16579. },
  16580. /**
  16581. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16582. * Default : (1.0, 1.0, 1.0)
  16583. */
  16584. set: function (newScaling) {
  16585. this._scaling = newScaling;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16591. /**
  16592. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16593. * It's null by default.
  16594. * 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)
  16595. */
  16596. get: function () {
  16597. return this._rotationQuaternion;
  16598. },
  16599. set: function (quaternion) {
  16600. this._rotationQuaternion = quaternion;
  16601. //reset the rotation vector.
  16602. if (quaternion && this.rotation.length()) {
  16603. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16604. }
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. Object.defineProperty(TransformNode.prototype, "forward", {
  16610. /**
  16611. * The forward direction of that transform in world space.
  16612. */
  16613. get: function () {
  16614. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16615. },
  16616. enumerable: true,
  16617. configurable: true
  16618. });
  16619. Object.defineProperty(TransformNode.prototype, "up", {
  16620. /**
  16621. * The up direction of that transform in world space.
  16622. */
  16623. get: function () {
  16624. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(TransformNode.prototype, "right", {
  16630. /**
  16631. * The right direction of that transform in world space.
  16632. */
  16633. get: function () {
  16634. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. /**
  16640. * Returns the latest update of the World matrix
  16641. * Returns a Matrix.
  16642. */
  16643. TransformNode.prototype.getWorldMatrix = function () {
  16644. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16645. this.computeWorldMatrix();
  16646. }
  16647. return this._worldMatrix;
  16648. };
  16649. /**
  16650. * Returns the latest update of the World matrix determinant.
  16651. */
  16652. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16653. return this._worldMatrixDeterminant;
  16654. };
  16655. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16656. /**
  16657. * Returns directly the latest state of the mesh World matrix.
  16658. * A Matrix is returned.
  16659. */
  16660. get: function () {
  16661. return this._worldMatrix;
  16662. },
  16663. enumerable: true,
  16664. configurable: true
  16665. });
  16666. /**
  16667. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16668. * Returns the TransformNode.
  16669. */
  16670. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16671. this._poseMatrix.copyFrom(matrix);
  16672. return this;
  16673. };
  16674. /**
  16675. * Returns the mesh Pose matrix.
  16676. * Returned object : Matrix
  16677. */
  16678. TransformNode.prototype.getPoseMatrix = function () {
  16679. return this._poseMatrix;
  16680. };
  16681. TransformNode.prototype._isSynchronized = function () {
  16682. if (this._isDirty) {
  16683. return false;
  16684. }
  16685. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16686. return false;
  16687. if (this._cache.pivotMatrixUpdated) {
  16688. return false;
  16689. }
  16690. if (this.infiniteDistance) {
  16691. return false;
  16692. }
  16693. if (!this._cache.position.equals(this.position))
  16694. return false;
  16695. if (this.rotationQuaternion) {
  16696. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16697. return false;
  16698. }
  16699. if (!this._cache.rotation.equals(this.rotation))
  16700. return false;
  16701. if (!this._cache.scaling.equals(this.scaling))
  16702. return false;
  16703. return true;
  16704. };
  16705. TransformNode.prototype._initCache = function () {
  16706. _super.prototype._initCache.call(this);
  16707. this._cache.localMatrixUpdated = false;
  16708. this._cache.position = BABYLON.Vector3.Zero();
  16709. this._cache.scaling = BABYLON.Vector3.Zero();
  16710. this._cache.rotation = BABYLON.Vector3.Zero();
  16711. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16712. this._cache.billboardMode = -1;
  16713. };
  16714. TransformNode.prototype.markAsDirty = function (property) {
  16715. if (property === "rotation") {
  16716. this.rotationQuaternion = null;
  16717. }
  16718. this._currentRenderId = Number.MAX_VALUE;
  16719. this._isDirty = true;
  16720. return this;
  16721. };
  16722. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16723. /**
  16724. * Returns the current mesh absolute position.
  16725. * Retuns a Vector3.
  16726. */
  16727. get: function () {
  16728. return this._absolutePosition;
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. /**
  16734. * Sets a new matrix to apply before all other transformation
  16735. * @param matrix defines the transform matrix
  16736. * @returns the current TransformNode
  16737. */
  16738. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16739. return this.setPivotMatrix(matrix, false);
  16740. };
  16741. /**
  16742. * Sets a new pivot matrix to the current node
  16743. * @param matrix defines the new pivot matrix to use
  16744. * @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
  16745. * @returns the current TransformNode
  16746. */
  16747. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16748. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16749. this._pivotMatrix = matrix.clone();
  16750. this._cache.pivotMatrixUpdated = true;
  16751. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16752. if (this._postMultiplyPivotMatrix) {
  16753. if (!this._pivotMatrixInverse) {
  16754. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16755. }
  16756. else {
  16757. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16758. }
  16759. }
  16760. return this;
  16761. };
  16762. /**
  16763. * Returns the mesh pivot matrix.
  16764. * Default : Identity.
  16765. * A Matrix is returned.
  16766. */
  16767. TransformNode.prototype.getPivotMatrix = function () {
  16768. return this._pivotMatrix;
  16769. };
  16770. /**
  16771. * Prevents the World matrix to be computed any longer.
  16772. * Returns the TransformNode.
  16773. */
  16774. TransformNode.prototype.freezeWorldMatrix = function () {
  16775. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16776. this.computeWorldMatrix(true);
  16777. this._isWorldMatrixFrozen = true;
  16778. return this;
  16779. };
  16780. /**
  16781. * Allows back the World matrix computation.
  16782. * Returns the TransformNode.
  16783. */
  16784. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16785. this._isWorldMatrixFrozen = false;
  16786. this.computeWorldMatrix(true);
  16787. return this;
  16788. };
  16789. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16790. /**
  16791. * True if the World matrix has been frozen.
  16792. * Returns a boolean.
  16793. */
  16794. get: function () {
  16795. return this._isWorldMatrixFrozen;
  16796. },
  16797. enumerable: true,
  16798. configurable: true
  16799. });
  16800. /**
  16801. * Retuns the mesh absolute position in the World.
  16802. * Returns a Vector3.
  16803. */
  16804. TransformNode.prototype.getAbsolutePosition = function () {
  16805. this.computeWorldMatrix();
  16806. return this._absolutePosition;
  16807. };
  16808. /**
  16809. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16810. * Returns the TransformNode.
  16811. */
  16812. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16813. if (!absolutePosition) {
  16814. return this;
  16815. }
  16816. var absolutePositionX;
  16817. var absolutePositionY;
  16818. var absolutePositionZ;
  16819. if (absolutePosition.x === undefined) {
  16820. if (arguments.length < 3) {
  16821. return this;
  16822. }
  16823. absolutePositionX = arguments[0];
  16824. absolutePositionY = arguments[1];
  16825. absolutePositionZ = arguments[2];
  16826. }
  16827. else {
  16828. absolutePositionX = absolutePosition.x;
  16829. absolutePositionY = absolutePosition.y;
  16830. absolutePositionZ = absolutePosition.z;
  16831. }
  16832. if (this.parent) {
  16833. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16834. invertParentWorldMatrix.invert();
  16835. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16836. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16837. }
  16838. else {
  16839. this.position.x = absolutePositionX;
  16840. this.position.y = absolutePositionY;
  16841. this.position.z = absolutePositionZ;
  16842. }
  16843. return this;
  16844. };
  16845. /**
  16846. * Sets the mesh position in its local space.
  16847. * Returns the TransformNode.
  16848. */
  16849. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16850. this.computeWorldMatrix();
  16851. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16852. return this;
  16853. };
  16854. /**
  16855. * Returns the mesh position in the local space from the current World matrix values.
  16856. * Returns a new Vector3.
  16857. */
  16858. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16859. this.computeWorldMatrix();
  16860. var invLocalWorldMatrix = this._localWorld.clone();
  16861. invLocalWorldMatrix.invert();
  16862. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16863. };
  16864. /**
  16865. * Translates the mesh along the passed Vector3 in its local space.
  16866. * Returns the TransformNode.
  16867. */
  16868. TransformNode.prototype.locallyTranslate = function (vector3) {
  16869. this.computeWorldMatrix(true);
  16870. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16871. return this;
  16872. };
  16873. /**
  16874. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16875. * @param targetPoint the position (must be in same space as current mesh) to look at
  16876. * @param yawCor optional yaw (y-axis) correction in radians
  16877. * @param pitchCor optional pitch (x-axis) correction in radians
  16878. * @param rollCor optional roll (z-axis) correction in radians
  16879. * @param space the choosen space of the target
  16880. * @returns the TransformNode.
  16881. */
  16882. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16883. if (yawCor === void 0) { yawCor = 0; }
  16884. if (pitchCor === void 0) { pitchCor = 0; }
  16885. if (rollCor === void 0) { rollCor = 0; }
  16886. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16887. var dv = TransformNode._lookAtVectorCache;
  16888. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16889. targetPoint.subtractToRef(pos, dv);
  16890. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16891. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16892. var pitch = Math.atan2(dv.y, len);
  16893. if (this.rotationQuaternion) {
  16894. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16895. }
  16896. else {
  16897. this.rotation.x = pitch + pitchCor;
  16898. this.rotation.y = yaw + yawCor;
  16899. this.rotation.z = rollCor;
  16900. }
  16901. return this;
  16902. };
  16903. /**
  16904. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16905. * This Vector3 is expressed in the World space.
  16906. */
  16907. TransformNode.prototype.getDirection = function (localAxis) {
  16908. var result = BABYLON.Vector3.Zero();
  16909. this.getDirectionToRef(localAxis, result);
  16910. return result;
  16911. };
  16912. /**
  16913. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16914. * localAxis is expressed in the mesh local space.
  16915. * result is computed in the Wordl space from the mesh World matrix.
  16916. * Returns the TransformNode.
  16917. */
  16918. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16919. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16920. return this;
  16921. };
  16922. /**
  16923. * Sets a new pivot point to the current node
  16924. * @param point defines the new pivot point to use
  16925. * @param space defines if the point is in world or local space (local by default)
  16926. * @returns the current TransformNode
  16927. */
  16928. TransformNode.prototype.setPivotPoint = function (point, space) {
  16929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16930. if (this.getScene().getRenderId() == 0) {
  16931. this.computeWorldMatrix(true);
  16932. }
  16933. var wm = this.getWorldMatrix();
  16934. if (space == BABYLON.Space.WORLD) {
  16935. var tmat = BABYLON.Tmp.Matrix[0];
  16936. wm.invertToRef(tmat);
  16937. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16938. }
  16939. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16940. };
  16941. /**
  16942. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16943. */
  16944. TransformNode.prototype.getPivotPoint = function () {
  16945. var point = BABYLON.Vector3.Zero();
  16946. this.getPivotPointToRef(point);
  16947. return point;
  16948. };
  16949. /**
  16950. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16951. * Returns the TransformNode.
  16952. */
  16953. TransformNode.prototype.getPivotPointToRef = function (result) {
  16954. result.x = -this._pivotMatrix.m[12];
  16955. result.y = -this._pivotMatrix.m[13];
  16956. result.z = -this._pivotMatrix.m[14];
  16957. return this;
  16958. };
  16959. /**
  16960. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16961. */
  16962. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16963. var point = BABYLON.Vector3.Zero();
  16964. this.getAbsolutePivotPointToRef(point);
  16965. return point;
  16966. };
  16967. /**
  16968. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16969. * Returns the TransformNode.
  16970. */
  16971. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16972. result.x = this._pivotMatrix.m[12];
  16973. result.y = this._pivotMatrix.m[13];
  16974. result.z = this._pivotMatrix.m[14];
  16975. this.getPivotPointToRef(result);
  16976. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16977. return this;
  16978. };
  16979. /**
  16980. * Defines the passed node as the parent of the current node.
  16981. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16982. * Returns the TransformNode.
  16983. */
  16984. TransformNode.prototype.setParent = function (node) {
  16985. if (node === null) {
  16986. var rotation = BABYLON.Tmp.Quaternion[0];
  16987. var position = BABYLON.Tmp.Vector3[0];
  16988. var scale = BABYLON.Tmp.Vector3[1];
  16989. if (this.parent && this.parent.computeWorldMatrix) {
  16990. this.parent.computeWorldMatrix(true);
  16991. }
  16992. this.computeWorldMatrix(true);
  16993. this.getWorldMatrix().decompose(scale, rotation, position);
  16994. if (this.rotationQuaternion) {
  16995. this.rotationQuaternion.copyFrom(rotation);
  16996. }
  16997. else {
  16998. rotation.toEulerAnglesToRef(this.rotation);
  16999. }
  17000. this.scaling.x = scale.x;
  17001. this.scaling.y = scale.y;
  17002. this.scaling.z = scale.z;
  17003. this.position.x = position.x;
  17004. this.position.y = position.y;
  17005. this.position.z = position.z;
  17006. }
  17007. else {
  17008. var rotation = BABYLON.Tmp.Quaternion[0];
  17009. var position = BABYLON.Tmp.Vector3[0];
  17010. var scale = BABYLON.Tmp.Vector3[1];
  17011. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17012. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17013. this.computeWorldMatrix(true);
  17014. node.computeWorldMatrix(true);
  17015. node.getWorldMatrix().invertToRef(invParentMatrix);
  17016. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17017. diffMatrix.decompose(scale, rotation, position);
  17018. if (this.rotationQuaternion) {
  17019. this.rotationQuaternion.copyFrom(rotation);
  17020. }
  17021. else {
  17022. rotation.toEulerAnglesToRef(this.rotation);
  17023. }
  17024. this.position.x = position.x;
  17025. this.position.y = position.y;
  17026. this.position.z = position.z;
  17027. this.scaling.x = scale.x;
  17028. this.scaling.y = scale.y;
  17029. this.scaling.z = scale.z;
  17030. }
  17031. this.parent = node;
  17032. return this;
  17033. };
  17034. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17035. get: function () {
  17036. return this._nonUniformScaling;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17042. if (this._nonUniformScaling === value) {
  17043. return false;
  17044. }
  17045. this._nonUniformScaling = true;
  17046. return true;
  17047. };
  17048. /**
  17049. * Attach the current TransformNode to another TransformNode associated with a bone
  17050. * @param bone Bone affecting the TransformNode
  17051. * @param affectedTransformNode TransformNode associated with the bone
  17052. */
  17053. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17054. this._transformToBoneReferal = affectedTransformNode;
  17055. this.parent = bone;
  17056. if (bone.getWorldMatrix().determinant() < 0) {
  17057. this.scalingDeterminant *= -1;
  17058. }
  17059. return this;
  17060. };
  17061. TransformNode.prototype.detachFromBone = function () {
  17062. if (!this.parent) {
  17063. return this;
  17064. }
  17065. if (this.parent.getWorldMatrix().determinant() < 0) {
  17066. this.scalingDeterminant *= -1;
  17067. }
  17068. this._transformToBoneReferal = null;
  17069. this.parent = null;
  17070. return this;
  17071. };
  17072. /**
  17073. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17074. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17075. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17076. * The passed axis is also normalized.
  17077. * Returns the TransformNode.
  17078. */
  17079. TransformNode.prototype.rotate = function (axis, amount, space) {
  17080. axis.normalize();
  17081. if (!this.rotationQuaternion) {
  17082. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17083. this.rotation = BABYLON.Vector3.Zero();
  17084. }
  17085. var rotationQuaternion;
  17086. if (!space || space === BABYLON.Space.LOCAL) {
  17087. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17088. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17089. }
  17090. else {
  17091. if (this.parent) {
  17092. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17093. invertParentWorldMatrix.invert();
  17094. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17095. }
  17096. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17097. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17098. }
  17099. return this;
  17100. };
  17101. /**
  17102. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17103. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17104. * The passed axis is also normalized.
  17105. * Returns the TransformNode.
  17106. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17107. */
  17108. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17109. axis.normalize();
  17110. if (!this.rotationQuaternion) {
  17111. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17112. this.rotation.copyFromFloats(0, 0, 0);
  17113. }
  17114. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17115. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17116. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17117. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17118. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17119. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17120. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17121. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17122. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17123. return this;
  17124. };
  17125. /**
  17126. * Translates the mesh along the axis vector for the passed distance in the given space.
  17127. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17128. * Returns the TransformNode.
  17129. */
  17130. TransformNode.prototype.translate = function (axis, distance, space) {
  17131. var displacementVector = axis.scale(distance);
  17132. if (!space || space === BABYLON.Space.LOCAL) {
  17133. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17134. this.setPositionWithLocalVector(tempV3);
  17135. }
  17136. else {
  17137. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17138. }
  17139. return this;
  17140. };
  17141. /**
  17142. * Adds a rotation step to the mesh current rotation.
  17143. * x, y, z are Euler angles expressed in radians.
  17144. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17145. * This means this rotation is made in the mesh local space only.
  17146. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17147. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17148. * ```javascript
  17149. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17150. * ```
  17151. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17152. * 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.
  17153. * Returns the TransformNode.
  17154. */
  17155. TransformNode.prototype.addRotation = function (x, y, z) {
  17156. var rotationQuaternion;
  17157. if (this.rotationQuaternion) {
  17158. rotationQuaternion = this.rotationQuaternion;
  17159. }
  17160. else {
  17161. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17162. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17163. }
  17164. var accumulation = BABYLON.Tmp.Quaternion[0];
  17165. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17166. rotationQuaternion.multiplyInPlace(accumulation);
  17167. if (!this.rotationQuaternion) {
  17168. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17169. }
  17170. return this;
  17171. };
  17172. /**
  17173. * Computes the mesh World matrix and returns it.
  17174. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17175. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17176. * If the parameter `force`is set to `true`, the actual computation is done.
  17177. * Returns the mesh World Matrix.
  17178. */
  17179. TransformNode.prototype.computeWorldMatrix = function (force) {
  17180. if (this._isWorldMatrixFrozen) {
  17181. return this._worldMatrix;
  17182. }
  17183. if (!force && this.isSynchronized(true)) {
  17184. this._currentRenderId = this.getScene().getRenderId();
  17185. return this._worldMatrix;
  17186. }
  17187. this._cache.position.copyFrom(this.position);
  17188. this._cache.scaling.copyFrom(this.scaling);
  17189. this._cache.pivotMatrixUpdated = false;
  17190. this._cache.billboardMode = this.billboardMode;
  17191. this._currentRenderId = this.getScene().getRenderId();
  17192. this._childRenderId = this.getScene().getRenderId();
  17193. this._isDirty = false;
  17194. // Scaling
  17195. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17196. // Rotation
  17197. //rotate, if quaternion is set and rotation was used
  17198. if (this.rotationQuaternion) {
  17199. var len = this.rotation.length();
  17200. if (len) {
  17201. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17202. this.rotation.copyFromFloats(0, 0, 0);
  17203. }
  17204. }
  17205. if (this.rotationQuaternion) {
  17206. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17207. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17208. }
  17209. else {
  17210. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17211. this._cache.rotation.copyFrom(this.rotation);
  17212. }
  17213. // Translation
  17214. var camera = this.getScene().activeCamera;
  17215. if (this.infiniteDistance && !this.parent && camera) {
  17216. var cameraWorldMatrix = camera.getWorldMatrix();
  17217. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17218. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17219. }
  17220. else {
  17221. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17222. }
  17223. // Composing transformations
  17224. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17225. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17226. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17227. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17228. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17229. // Need to decompose each rotation here
  17230. var currentPosition = BABYLON.Tmp.Vector3[3];
  17231. if (this.parent && this.parent.getWorldMatrix) {
  17232. if (this._transformToBoneReferal) {
  17233. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17234. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17235. }
  17236. else {
  17237. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17238. }
  17239. }
  17240. else {
  17241. currentPosition.copyFrom(this.position);
  17242. }
  17243. currentPosition.subtractInPlace(camera.globalPosition);
  17244. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17245. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17246. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17247. }
  17248. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17249. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17250. }
  17251. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17252. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17253. }
  17254. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17255. }
  17256. else {
  17257. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17258. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17259. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17260. }
  17261. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17262. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17263. }
  17264. // Local world
  17265. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17266. // Parent
  17267. if (this.parent && this.parent.getWorldMatrix) {
  17268. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17269. if (this._transformToBoneReferal) {
  17270. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17271. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17272. }
  17273. else {
  17274. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17275. }
  17276. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17277. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17278. this._worldMatrix.copyFrom(this._localWorld);
  17279. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17280. }
  17281. else {
  17282. if (this._transformToBoneReferal) {
  17283. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17284. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17285. }
  17286. else {
  17287. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17288. }
  17289. }
  17290. this._markSyncedWithParent();
  17291. }
  17292. else {
  17293. this._worldMatrix.copyFrom(this._localWorld);
  17294. }
  17295. // Post multiply inverse of pivotMatrix
  17296. if (this._postMultiplyPivotMatrix) {
  17297. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17298. }
  17299. // Normal matrix
  17300. if (this.scaling.isNonUniform) {
  17301. this._updateNonUniformScalingState(true);
  17302. }
  17303. else if (this.parent && this.parent._nonUniformScaling) {
  17304. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17305. }
  17306. else {
  17307. this._updateNonUniformScalingState(false);
  17308. }
  17309. this._afterComputeWorldMatrix();
  17310. // Absolute position
  17311. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17312. // Callbacks
  17313. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17314. if (!this._poseMatrix) {
  17315. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17316. }
  17317. // Cache the determinant
  17318. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17319. return this._worldMatrix;
  17320. };
  17321. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17322. };
  17323. /**
  17324. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17325. * @param func: callback function to add
  17326. *
  17327. * Returns the TransformNode.
  17328. */
  17329. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17330. this.onAfterWorldMatrixUpdateObservable.add(func);
  17331. return this;
  17332. };
  17333. /**
  17334. * Removes a registered callback function.
  17335. * Returns the TransformNode.
  17336. */
  17337. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17338. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17339. return this;
  17340. };
  17341. /**
  17342. * Clone the current transform node
  17343. * Returns the new transform node
  17344. * @param name Name of the new clone
  17345. * @param newParent New parent for the clone
  17346. * @param doNotCloneChildren Do not clone children hierarchy
  17347. */
  17348. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17349. var _this = this;
  17350. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17351. result.name = name;
  17352. result.id = name;
  17353. if (newParent) {
  17354. result.parent = newParent;
  17355. }
  17356. if (!doNotCloneChildren) {
  17357. // Children
  17358. var directDescendants = this.getDescendants(true);
  17359. for (var index = 0; index < directDescendants.length; index++) {
  17360. var child = directDescendants[index];
  17361. if (child.clone) {
  17362. child.clone(name + "." + child.name, result);
  17363. }
  17364. }
  17365. }
  17366. return result;
  17367. };
  17368. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17369. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17370. serializationObject.type = this.getClassName();
  17371. // Parent
  17372. if (this.parent) {
  17373. serializationObject.parentId = this.parent.id;
  17374. }
  17375. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17377. }
  17378. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17379. serializationObject.isEnabled = this.isEnabled();
  17380. // Parent
  17381. if (this.parent) {
  17382. serializationObject.parentId = this.parent.id;
  17383. }
  17384. return serializationObject;
  17385. };
  17386. // Statics
  17387. /**
  17388. * Returns a new TransformNode object parsed from the source provided.
  17389. * The parameter `parsedMesh` is the source.
  17390. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17391. */
  17392. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17393. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17394. if (BABYLON.Tags) {
  17395. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17396. }
  17397. if (parsedTransformNode.localMatrix) {
  17398. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17399. }
  17400. else if (parsedTransformNode.pivotMatrix) {
  17401. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17402. }
  17403. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17404. // Parent
  17405. if (parsedTransformNode.parentId) {
  17406. transformNode._waitingParentId = parsedTransformNode.parentId;
  17407. }
  17408. return transformNode;
  17409. };
  17410. /**
  17411. * Releases resources associated with this transform node.
  17412. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17413. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17414. */
  17415. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17416. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17417. // Animations
  17418. this.getScene().stopAnimation(this);
  17419. // Remove from scene
  17420. this.getScene().removeTransformNode(this);
  17421. this.onAfterWorldMatrixUpdateObservable.clear();
  17422. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17423. };
  17424. // Statics
  17425. TransformNode.BILLBOARDMODE_NONE = 0;
  17426. TransformNode.BILLBOARDMODE_X = 1;
  17427. TransformNode.BILLBOARDMODE_Y = 2;
  17428. TransformNode.BILLBOARDMODE_Z = 4;
  17429. TransformNode.BILLBOARDMODE_ALL = 7;
  17430. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17431. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17432. __decorate([
  17433. BABYLON.serializeAsVector3()
  17434. ], TransformNode.prototype, "_rotation", void 0);
  17435. __decorate([
  17436. BABYLON.serializeAsQuaternion()
  17437. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17438. __decorate([
  17439. BABYLON.serializeAsVector3()
  17440. ], TransformNode.prototype, "_scaling", void 0);
  17441. __decorate([
  17442. BABYLON.serialize()
  17443. ], TransformNode.prototype, "billboardMode", void 0);
  17444. __decorate([
  17445. BABYLON.serialize()
  17446. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17447. __decorate([
  17448. BABYLON.serialize()
  17449. ], TransformNode.prototype, "infiniteDistance", void 0);
  17450. __decorate([
  17451. BABYLON.serializeAsVector3()
  17452. ], TransformNode.prototype, "position", void 0);
  17453. return TransformNode;
  17454. }(BABYLON.Node));
  17455. BABYLON.TransformNode = TransformNode;
  17456. })(BABYLON || (BABYLON = {}));
  17457. //# sourceMappingURL=babylon.transformNode.js.map
  17458. "use strict";
  17459. var BABYLON;
  17460. (function (BABYLON) {
  17461. var AbstractMesh = /** @class */ (function (_super) {
  17462. __extends(AbstractMesh, _super);
  17463. // Constructor
  17464. function AbstractMesh(name, scene) {
  17465. if (scene === void 0) { scene = null; }
  17466. var _this = _super.call(this, name, scene, false) || this;
  17467. _this._facetNb = 0; // facet number
  17468. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17469. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17470. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17471. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17472. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17473. _this._subDiv = {
  17474. max: 1,
  17475. X: 1,
  17476. Y: 1,
  17477. Z: 1
  17478. };
  17479. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17480. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17481. // Events
  17482. /**
  17483. * An event triggered when this mesh collides with another one
  17484. */
  17485. _this.onCollideObservable = new BABYLON.Observable();
  17486. /**
  17487. * An event triggered when the collision's position changes
  17488. */
  17489. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17490. /**
  17491. * An event triggered when material is changed
  17492. */
  17493. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17494. // Properties
  17495. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17496. /**
  17497. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17498. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17499. * or
  17500. * 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.
  17501. * for more info check WebGl documentations
  17502. */
  17503. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17504. /**
  17505. * 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:
  17506. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17507. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17508. * 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.
  17509. */
  17510. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17511. /**
  17512. * 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.
  17513. * The default value is -1 which means don't break the query and wait till the result.
  17514. */
  17515. _this.occlusionRetryCount = -1;
  17516. _this._occlusionInternalRetryCounter = 0;
  17517. _this._isOccluded = false;
  17518. _this._isOcclusionQueryInProgress = false;
  17519. _this._visibility = 1.0;
  17520. _this.alphaIndex = Number.MAX_VALUE;
  17521. _this.isVisible = true;
  17522. _this.isPickable = true;
  17523. _this.showBoundingBox = false;
  17524. _this.showSubMeshesBoundingBox = false;
  17525. _this.isBlocker = false;
  17526. _this.enablePointerMoveEvents = false;
  17527. _this.renderingGroupId = 0;
  17528. _this._receiveShadows = false;
  17529. _this.renderOutline = false;
  17530. _this.outlineColor = BABYLON.Color3.Red();
  17531. _this.outlineWidth = 0.02;
  17532. _this.renderOverlay = false;
  17533. _this.overlayColor = BABYLON.Color3.Red();
  17534. _this.overlayAlpha = 0.5;
  17535. _this._hasVertexAlpha = false;
  17536. _this._useVertexColors = true;
  17537. _this._computeBonesUsingShaders = true;
  17538. _this._numBoneInfluencers = 4;
  17539. _this._applyFog = true;
  17540. _this.useOctreeForRenderingSelection = true;
  17541. _this.useOctreeForPicking = true;
  17542. _this.useOctreeForCollisions = true;
  17543. _this._layerMask = 0x0FFFFFFF;
  17544. /**
  17545. * True if the mesh must be rendered in any case.
  17546. */
  17547. _this.alwaysSelectAsActiveMesh = false;
  17548. /**
  17549. * This scene's action manager
  17550. */
  17551. _this.actionManager = null;
  17552. // Physics
  17553. _this.physicsImpostor = null;
  17554. // Collisions
  17555. _this._checkCollisions = false;
  17556. _this._collisionMask = -1;
  17557. _this._collisionGroup = -1;
  17558. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17559. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17560. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17561. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17562. // Edges
  17563. _this.edgesWidth = 1;
  17564. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17565. // Cache
  17566. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17567. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17568. _this._renderId = 0;
  17569. _this._intersectionsInProgress = new Array();
  17570. _this._unIndexed = false;
  17571. _this._lightSources = new Array();
  17572. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17573. if (collidedMesh === void 0) { collidedMesh = null; }
  17574. //TODO move this to the collision coordinator!
  17575. if (_this.getScene().workerCollisions)
  17576. newPosition.multiplyInPlace(_this._collider._radius);
  17577. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17578. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17579. _this.position.addInPlace(_this._diffPositionForCollisions);
  17580. }
  17581. if (collidedMesh) {
  17582. _this.onCollideObservable.notifyObservers(collidedMesh);
  17583. }
  17584. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17585. };
  17586. _this.getScene().addMesh(_this);
  17587. _this._resyncLightSources();
  17588. return _this;
  17589. }
  17590. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17591. get: function () {
  17592. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17593. },
  17594. enumerable: true,
  17595. configurable: true
  17596. });
  17597. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17598. get: function () {
  17599. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17605. get: function () {
  17606. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17607. },
  17608. enumerable: true,
  17609. configurable: true
  17610. });
  17611. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17612. get: function () {
  17613. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17614. },
  17615. enumerable: true,
  17616. configurable: true
  17617. });
  17618. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17619. get: function () {
  17620. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17626. /**
  17627. * Read-only : the number of facets in the mesh
  17628. */
  17629. get: function () {
  17630. return this._facetNb;
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17636. /**
  17637. * The number (integer) of subdivisions per axis in the partioning space
  17638. */
  17639. get: function () {
  17640. return this._partitioningSubdivisions;
  17641. },
  17642. set: function (nb) {
  17643. this._partitioningSubdivisions = nb;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17649. /**
  17650. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17651. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17652. */
  17653. get: function () {
  17654. return this._partitioningBBoxRatio;
  17655. },
  17656. set: function (ratio) {
  17657. this._partitioningBBoxRatio = ratio;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17663. /**
  17664. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17665. * Works only for updatable meshes.
  17666. * Doesn't work with multi-materials.
  17667. */
  17668. get: function () {
  17669. return this._facetDepthSort;
  17670. },
  17671. set: function (sort) {
  17672. this._facetDepthSort = sort;
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17678. /**
  17679. * The location (Vector3) where the facet depth sort must be computed from.
  17680. * By default, the active camera position.
  17681. * Used only when facet depth sort is enabled.
  17682. */
  17683. get: function () {
  17684. return this._facetDepthSortFrom;
  17685. },
  17686. set: function (location) {
  17687. this._facetDepthSortFrom = location;
  17688. },
  17689. enumerable: true,
  17690. configurable: true
  17691. });
  17692. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17693. /**
  17694. * Read-only boolean : is the feature facetData enabled ?
  17695. */
  17696. get: function () {
  17697. return this._facetDataEnabled;
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17703. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17704. return false;
  17705. }
  17706. this._markSubMeshesAsMiscDirty();
  17707. return true;
  17708. };
  17709. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17710. set: function (callback) {
  17711. if (this._onCollideObserver) {
  17712. this.onCollideObservable.remove(this._onCollideObserver);
  17713. }
  17714. this._onCollideObserver = this.onCollideObservable.add(callback);
  17715. },
  17716. enumerable: true,
  17717. configurable: true
  17718. });
  17719. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17720. set: function (callback) {
  17721. if (this._onCollisionPositionChangeObserver) {
  17722. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17723. }
  17724. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17730. /**
  17731. * 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.
  17732. */
  17733. get: function () {
  17734. return this._isOccluded;
  17735. },
  17736. set: function (value) {
  17737. this._isOccluded = value;
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17743. /**
  17744. * Flag to check the progress status of the query
  17745. */
  17746. get: function () {
  17747. return this._isOcclusionQueryInProgress;
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17753. /**
  17754. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17755. */
  17756. get: function () {
  17757. return this._visibility;
  17758. },
  17759. /**
  17760. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17761. */
  17762. set: function (value) {
  17763. if (this._visibility === value) {
  17764. return;
  17765. }
  17766. this._visibility = value;
  17767. this._markSubMeshesAsMiscDirty();
  17768. },
  17769. enumerable: true,
  17770. configurable: true
  17771. });
  17772. Object.defineProperty(AbstractMesh.prototype, "material", {
  17773. get: function () {
  17774. return this._material;
  17775. },
  17776. set: function (value) {
  17777. if (this._material === value) {
  17778. return;
  17779. }
  17780. this._material = value;
  17781. if (this.onMaterialChangedObservable.hasObservers) {
  17782. this.onMaterialChangedObservable.notifyObservers(this);
  17783. }
  17784. if (!this.subMeshes) {
  17785. return;
  17786. }
  17787. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17788. var subMesh = _a[_i];
  17789. subMesh.setEffect(null);
  17790. }
  17791. },
  17792. enumerable: true,
  17793. configurable: true
  17794. });
  17795. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17796. get: function () {
  17797. return this._receiveShadows;
  17798. },
  17799. set: function (value) {
  17800. if (this._receiveShadows === value) {
  17801. return;
  17802. }
  17803. this._receiveShadows = value;
  17804. this._markSubMeshesAsLightDirty();
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17810. get: function () {
  17811. return this._hasVertexAlpha;
  17812. },
  17813. set: function (value) {
  17814. if (this._hasVertexAlpha === value) {
  17815. return;
  17816. }
  17817. this._hasVertexAlpha = value;
  17818. this._markSubMeshesAsAttributesDirty();
  17819. this._markSubMeshesAsMiscDirty();
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17825. get: function () {
  17826. return this._useVertexColors;
  17827. },
  17828. set: function (value) {
  17829. if (this._useVertexColors === value) {
  17830. return;
  17831. }
  17832. this._useVertexColors = value;
  17833. this._markSubMeshesAsAttributesDirty();
  17834. },
  17835. enumerable: true,
  17836. configurable: true
  17837. });
  17838. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17839. get: function () {
  17840. return this._computeBonesUsingShaders;
  17841. },
  17842. set: function (value) {
  17843. if (this._computeBonesUsingShaders === value) {
  17844. return;
  17845. }
  17846. this._computeBonesUsingShaders = value;
  17847. this._markSubMeshesAsAttributesDirty();
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17853. get: function () {
  17854. return this._numBoneInfluencers;
  17855. },
  17856. set: function (value) {
  17857. if (this._numBoneInfluencers === value) {
  17858. return;
  17859. }
  17860. this._numBoneInfluencers = value;
  17861. this._markSubMeshesAsAttributesDirty();
  17862. },
  17863. enumerable: true,
  17864. configurable: true
  17865. });
  17866. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17867. get: function () {
  17868. return this._applyFog;
  17869. },
  17870. set: function (value) {
  17871. if (this._applyFog === value) {
  17872. return;
  17873. }
  17874. this._applyFog = value;
  17875. this._markSubMeshesAsMiscDirty();
  17876. },
  17877. enumerable: true,
  17878. configurable: true
  17879. });
  17880. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17881. get: function () {
  17882. return this._layerMask;
  17883. },
  17884. set: function (value) {
  17885. if (value === this._layerMask) {
  17886. return;
  17887. }
  17888. this._layerMask = value;
  17889. this._resyncLightSources();
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17895. get: function () {
  17896. return this._collisionMask;
  17897. },
  17898. set: function (mask) {
  17899. this._collisionMask = !isNaN(mask) ? mask : -1;
  17900. },
  17901. enumerable: true,
  17902. configurable: true
  17903. });
  17904. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17905. get: function () {
  17906. return this._collisionGroup;
  17907. },
  17908. set: function (mask) {
  17909. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17915. get: function () {
  17916. return null;
  17917. },
  17918. enumerable: true,
  17919. configurable: true
  17920. });
  17921. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17922. get: function () {
  17923. return this._skeleton;
  17924. },
  17925. set: function (value) {
  17926. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17927. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17928. }
  17929. if (value && value.needInitialSkinMatrix) {
  17930. value._registerMeshWithPoseMatrix(this);
  17931. }
  17932. this._skeleton = value;
  17933. if (!this._skeleton) {
  17934. this._bonesTransformMatrices = null;
  17935. }
  17936. this._markSubMeshesAsAttributesDirty();
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. /**
  17942. * Returns the string "AbstractMesh"
  17943. */
  17944. AbstractMesh.prototype.getClassName = function () {
  17945. return "AbstractMesh";
  17946. };
  17947. /**
  17948. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17949. */
  17950. AbstractMesh.prototype.toString = function (fullDetails) {
  17951. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17952. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17953. if (this._skeleton) {
  17954. ret += ", skeleton: " + this._skeleton.name;
  17955. }
  17956. if (fullDetails) {
  17957. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17958. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17959. }
  17960. return ret;
  17961. };
  17962. AbstractMesh.prototype._rebuild = function () {
  17963. if (this._occlusionQuery) {
  17964. this._occlusionQuery = null;
  17965. }
  17966. if (this._edgesRenderer) {
  17967. this._edgesRenderer._rebuild();
  17968. }
  17969. if (!this.subMeshes) {
  17970. return;
  17971. }
  17972. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17973. var subMesh = _a[_i];
  17974. subMesh._rebuild();
  17975. }
  17976. };
  17977. AbstractMesh.prototype._resyncLightSources = function () {
  17978. this._lightSources.length = 0;
  17979. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17980. var light = _a[_i];
  17981. if (!light.isEnabled()) {
  17982. continue;
  17983. }
  17984. if (light.canAffectMesh(this)) {
  17985. this._lightSources.push(light);
  17986. }
  17987. }
  17988. this._markSubMeshesAsLightDirty();
  17989. };
  17990. AbstractMesh.prototype._resyncLighSource = function (light) {
  17991. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17992. var index = this._lightSources.indexOf(light);
  17993. if (index === -1) {
  17994. if (!isIn) {
  17995. return;
  17996. }
  17997. this._lightSources.push(light);
  17998. }
  17999. else {
  18000. if (isIn) {
  18001. return;
  18002. }
  18003. this._lightSources.splice(index, 1);
  18004. }
  18005. this._markSubMeshesAsLightDirty();
  18006. };
  18007. AbstractMesh.prototype._removeLightSource = function (light) {
  18008. var index = this._lightSources.indexOf(light);
  18009. if (index === -1) {
  18010. return;
  18011. }
  18012. this._lightSources.splice(index, 1);
  18013. this._markSubMeshesAsLightDirty();
  18014. };
  18015. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18016. if (!this.subMeshes) {
  18017. return;
  18018. }
  18019. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18020. var subMesh = _a[_i];
  18021. if (subMesh._materialDefines) {
  18022. func(subMesh._materialDefines);
  18023. }
  18024. }
  18025. };
  18026. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18027. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18028. };
  18029. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18030. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18031. };
  18032. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18033. if (!this.subMeshes) {
  18034. return;
  18035. }
  18036. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18037. var subMesh = _a[_i];
  18038. var material = subMesh.getMaterial();
  18039. if (material) {
  18040. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18041. }
  18042. }
  18043. };
  18044. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18045. /**
  18046. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18047. * Default : (1.0, 1.0, 1.0)
  18048. */
  18049. get: function () {
  18050. return this._scaling;
  18051. },
  18052. /**
  18053. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18054. * Default : (1.0, 1.0, 1.0)
  18055. */
  18056. set: function (newScaling) {
  18057. this._scaling = newScaling;
  18058. if (this.physicsImpostor) {
  18059. this.physicsImpostor.forceUpdate();
  18060. }
  18061. },
  18062. enumerable: true,
  18063. configurable: true
  18064. });
  18065. // Methods
  18066. /**
  18067. * Disables the mesh edger rendering mode.
  18068. * Returns the AbstractMesh.
  18069. */
  18070. AbstractMesh.prototype.disableEdgesRendering = function () {
  18071. if (this._edgesRenderer) {
  18072. this._edgesRenderer.dispose();
  18073. this._edgesRenderer = null;
  18074. }
  18075. return this;
  18076. };
  18077. /**
  18078. * Enables the edge rendering mode on the mesh.
  18079. * This mode makes the mesh edges visible.
  18080. * Returns the AbstractMesh.
  18081. */
  18082. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18083. if (epsilon === void 0) { epsilon = 0.95; }
  18084. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18085. this.disableEdgesRendering();
  18086. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18087. return this;
  18088. };
  18089. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18090. /**
  18091. * Returns true if the mesh is blocked. Used by the class Mesh.
  18092. * Returns the boolean `false` by default.
  18093. */
  18094. get: function () {
  18095. return false;
  18096. },
  18097. enumerable: true,
  18098. configurable: true
  18099. });
  18100. /**
  18101. * Returns the mesh itself by default, used by the class Mesh.
  18102. * Returned type : AbstractMesh
  18103. */
  18104. AbstractMesh.prototype.getLOD = function (camera) {
  18105. return this;
  18106. };
  18107. /**
  18108. * Returns 0 by default, used by the class Mesh.
  18109. * Returns an integer.
  18110. */
  18111. AbstractMesh.prototype.getTotalVertices = function () {
  18112. return 0;
  18113. };
  18114. /**
  18115. * Returns null by default, used by the class Mesh.
  18116. * Returned type : integer array
  18117. */
  18118. AbstractMesh.prototype.getIndices = function () {
  18119. return null;
  18120. };
  18121. /**
  18122. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18123. * Returned type : float array or Float32Array
  18124. */
  18125. AbstractMesh.prototype.getVerticesData = function (kind) {
  18126. return null;
  18127. };
  18128. /**
  18129. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18130. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18131. * The `data` are either a numeric array either a Float32Array.
  18132. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18133. * 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).
  18134. * Note that a new underlying VertexBuffer object is created each call.
  18135. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18136. *
  18137. * Possible `kind` values :
  18138. * - BABYLON.VertexBuffer.PositionKind
  18139. * - BABYLON.VertexBuffer.UVKind
  18140. * - BABYLON.VertexBuffer.UV2Kind
  18141. * - BABYLON.VertexBuffer.UV3Kind
  18142. * - BABYLON.VertexBuffer.UV4Kind
  18143. * - BABYLON.VertexBuffer.UV5Kind
  18144. * - BABYLON.VertexBuffer.UV6Kind
  18145. * - BABYLON.VertexBuffer.ColorKind
  18146. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18147. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18148. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18149. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18150. *
  18151. * Returns the Mesh.
  18152. */
  18153. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18154. return this;
  18155. };
  18156. /**
  18157. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18158. * If the mesh has no geometry, it is simply returned as it is.
  18159. * The `data` are either a numeric array either a Float32Array.
  18160. * No new underlying VertexBuffer object is created.
  18161. * 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.
  18162. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18163. *
  18164. * Possible `kind` values :
  18165. * - BABYLON.VertexBuffer.PositionKind
  18166. * - BABYLON.VertexBuffer.UVKind
  18167. * - BABYLON.VertexBuffer.UV2Kind
  18168. * - BABYLON.VertexBuffer.UV3Kind
  18169. * - BABYLON.VertexBuffer.UV4Kind
  18170. * - BABYLON.VertexBuffer.UV5Kind
  18171. * - BABYLON.VertexBuffer.UV6Kind
  18172. * - BABYLON.VertexBuffer.ColorKind
  18173. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18174. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18175. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18176. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18177. *
  18178. * Returns the Mesh.
  18179. */
  18180. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18181. return this;
  18182. };
  18183. /**
  18184. * Sets the mesh indices.
  18185. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18186. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18187. * This method creates a new index buffer each call.
  18188. * Returns the Mesh.
  18189. */
  18190. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18191. return this;
  18192. };
  18193. /** Returns false by default, used by the class Mesh.
  18194. * Returns a boolean
  18195. */
  18196. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18197. return false;
  18198. };
  18199. /**
  18200. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18201. * Returns a BoundingInfo
  18202. */
  18203. AbstractMesh.prototype.getBoundingInfo = function () {
  18204. if (this._masterMesh) {
  18205. return this._masterMesh.getBoundingInfo();
  18206. }
  18207. if (!this._boundingInfo) {
  18208. // this._boundingInfo is being created here
  18209. this._updateBoundingInfo();
  18210. }
  18211. // cannot be null.
  18212. return this._boundingInfo;
  18213. };
  18214. /**
  18215. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18216. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18217. */
  18218. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18219. if (includeDescendants === void 0) { includeDescendants = true; }
  18220. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18221. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18222. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18223. if (maxDimension === 0) {
  18224. return this;
  18225. }
  18226. var scale = 1 / maxDimension;
  18227. this.scaling.scaleInPlace(scale);
  18228. return this;
  18229. };
  18230. /**
  18231. * Sets a mesh new object BoundingInfo.
  18232. * Returns the AbstractMesh.
  18233. */
  18234. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18235. this._boundingInfo = boundingInfo;
  18236. return this;
  18237. };
  18238. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18239. get: function () {
  18240. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18241. },
  18242. enumerable: true,
  18243. configurable: true
  18244. });
  18245. AbstractMesh.prototype._preActivate = function () {
  18246. };
  18247. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18248. };
  18249. AbstractMesh.prototype._activate = function (renderId) {
  18250. this._renderId = renderId;
  18251. };
  18252. /**
  18253. * Returns the latest update of the World matrix
  18254. * Returns a Matrix.
  18255. */
  18256. AbstractMesh.prototype.getWorldMatrix = function () {
  18257. if (this._masterMesh) {
  18258. return this._masterMesh.getWorldMatrix();
  18259. }
  18260. return _super.prototype.getWorldMatrix.call(this);
  18261. };
  18262. /**
  18263. * Returns the latest update of the World matrix determinant.
  18264. */
  18265. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18266. if (this._masterMesh) {
  18267. return this._masterMesh._getWorldMatrixDeterminant();
  18268. }
  18269. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18270. };
  18271. // ================================== Point of View Movement =================================
  18272. /**
  18273. * Perform relative position change from the point of view of behind the front of the mesh.
  18274. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18275. * Supports definition of mesh facing forward or backward.
  18276. * @param {number} amountRight
  18277. * @param {number} amountUp
  18278. * @param {number} amountForward
  18279. *
  18280. * Returns the AbstractMesh.
  18281. */
  18282. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18283. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18284. return this;
  18285. };
  18286. /**
  18287. * Calculate relative position change from the point of view of behind the front of the mesh.
  18288. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18289. * Supports definition of mesh facing forward or backward.
  18290. * @param {number} amountRight
  18291. * @param {number} amountUp
  18292. * @param {number} amountForward
  18293. *
  18294. * Returns a new Vector3.
  18295. */
  18296. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18297. var rotMatrix = new BABYLON.Matrix();
  18298. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18299. rotQuaternion.toRotationMatrix(rotMatrix);
  18300. var translationDelta = BABYLON.Vector3.Zero();
  18301. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18302. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18303. return translationDelta;
  18304. };
  18305. // ================================== Point of View Rotation =================================
  18306. /**
  18307. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18308. * Supports definition of mesh facing forward or backward.
  18309. * @param {number} flipBack
  18310. * @param {number} twirlClockwise
  18311. * @param {number} tiltRight
  18312. *
  18313. * Returns the AbstractMesh.
  18314. */
  18315. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18316. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18317. return this;
  18318. };
  18319. /**
  18320. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18321. * Supports definition of mesh facing forward or backward.
  18322. * @param {number} flipBack
  18323. * @param {number} twirlClockwise
  18324. * @param {number} tiltRight
  18325. *
  18326. * Returns a new Vector3.
  18327. */
  18328. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18329. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18330. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18331. };
  18332. /**
  18333. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18334. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18335. */
  18336. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18337. if (includeDescendants === void 0) { includeDescendants = true; }
  18338. this.computeWorldMatrix(true);
  18339. var min;
  18340. var max;
  18341. var boundingInfo = this.getBoundingInfo();
  18342. if (!this.subMeshes) {
  18343. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18344. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18345. }
  18346. else {
  18347. min = boundingInfo.boundingBox.minimumWorld;
  18348. max = boundingInfo.boundingBox.maximumWorld;
  18349. }
  18350. if (includeDescendants) {
  18351. var descendants = this.getDescendants(false);
  18352. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18353. var descendant = descendants_1[_i];
  18354. var childMesh = descendant;
  18355. childMesh.computeWorldMatrix(true);
  18356. //make sure we have the needed params to get mix and max
  18357. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18358. continue;
  18359. }
  18360. var childBoundingInfo = childMesh.getBoundingInfo();
  18361. var boundingBox = childBoundingInfo.boundingBox;
  18362. var minBox = boundingBox.minimumWorld;
  18363. var maxBox = boundingBox.maximumWorld;
  18364. BABYLON.Tools.CheckExtends(minBox, min, max);
  18365. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18366. }
  18367. }
  18368. return {
  18369. min: min,
  18370. max: max
  18371. };
  18372. };
  18373. /**
  18374. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18375. * Returns the AbstractMesh.
  18376. */
  18377. AbstractMesh.prototype._updateBoundingInfo = function () {
  18378. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18379. this._boundingInfo.update(this.worldMatrixFromCache);
  18380. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18381. return this;
  18382. };
  18383. /**
  18384. * Update a mesh's children BoundingInfo objects only.
  18385. * Returns the AbstractMesh.
  18386. */
  18387. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18388. if (!this.subMeshes) {
  18389. return this;
  18390. }
  18391. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18392. var subMesh = this.subMeshes[subIndex];
  18393. if (!subMesh.IsGlobal) {
  18394. subMesh.updateBoundingInfo(matrix);
  18395. }
  18396. }
  18397. return this;
  18398. };
  18399. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18400. // Bounding info
  18401. this._updateBoundingInfo();
  18402. };
  18403. /**
  18404. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18405. * A mesh is in the frustum if its bounding box intersects the frustum.
  18406. * Boolean returned.
  18407. */
  18408. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18409. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18410. };
  18411. /**
  18412. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18413. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18414. * Boolean returned.
  18415. */
  18416. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18417. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18418. ;
  18419. };
  18420. /**
  18421. * True if the mesh intersects another mesh or a SolidParticle object.
  18422. * 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)
  18423. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18424. * Returns a boolean.
  18425. */
  18426. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18427. if (precise === void 0) { precise = false; }
  18428. if (!this._boundingInfo || !mesh._boundingInfo) {
  18429. return false;
  18430. }
  18431. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18432. return true;
  18433. }
  18434. if (includeDescendants) {
  18435. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18436. var child = _a[_i];
  18437. if (child.intersectsMesh(mesh, precise, true)) {
  18438. return true;
  18439. }
  18440. }
  18441. }
  18442. return false;
  18443. };
  18444. /**
  18445. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18446. * Returns a boolean.
  18447. */
  18448. AbstractMesh.prototype.intersectsPoint = function (point) {
  18449. if (!this._boundingInfo) {
  18450. return false;
  18451. }
  18452. return this._boundingInfo.intersectsPoint(point);
  18453. };
  18454. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18455. return this.physicsImpostor;
  18456. };
  18457. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18458. if (camera === void 0) { camera = null; }
  18459. if (!camera) {
  18460. camera = this.getScene().activeCamera;
  18461. }
  18462. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18463. };
  18464. /**
  18465. * Returns the distance from the mesh to the active camera.
  18466. * Returns a float.
  18467. */
  18468. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18469. if (camera === void 0) { camera = null; }
  18470. if (!camera) {
  18471. camera = this.getScene().activeCamera;
  18472. }
  18473. return this.absolutePosition.subtract(camera.position).length();
  18474. };
  18475. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18476. if (!this.physicsImpostor) {
  18477. return this;
  18478. }
  18479. this.physicsImpostor.applyImpulse(force, contactPoint);
  18480. return this;
  18481. };
  18482. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18483. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18484. return this;
  18485. }
  18486. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18487. mainPivot: pivot1,
  18488. connectedPivot: pivot2,
  18489. nativeParams: options
  18490. });
  18491. return this;
  18492. };
  18493. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18494. // Collisions
  18495. /**
  18496. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18497. * Default `false`.
  18498. */
  18499. get: function () {
  18500. return this._checkCollisions;
  18501. },
  18502. set: function (collisionEnabled) {
  18503. this._checkCollisions = collisionEnabled;
  18504. if (this.getScene().workerCollisions) {
  18505. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18506. }
  18507. },
  18508. enumerable: true,
  18509. configurable: true
  18510. });
  18511. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18512. /**
  18513. * Gets Collider object used to compute collisions (not physics)
  18514. */
  18515. get: function () {
  18516. return this._collider;
  18517. },
  18518. enumerable: true,
  18519. configurable: true
  18520. });
  18521. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18522. var globalPosition = this.getAbsolutePosition();
  18523. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18524. if (!this._collider) {
  18525. this._collider = new BABYLON.Collider();
  18526. }
  18527. this._collider._radius = this.ellipsoid;
  18528. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18529. return this;
  18530. };
  18531. // Submeshes octree
  18532. /**
  18533. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18534. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18535. * Returns an Octree of submeshes.
  18536. */
  18537. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18538. if (maxCapacity === void 0) { maxCapacity = 64; }
  18539. if (maxDepth === void 0) { maxDepth = 2; }
  18540. if (!this._submeshesOctree) {
  18541. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18542. }
  18543. this.computeWorldMatrix(true);
  18544. var boundingInfo = this.getBoundingInfo();
  18545. // Update octree
  18546. var bbox = boundingInfo.boundingBox;
  18547. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18548. return this._submeshesOctree;
  18549. };
  18550. // Collisions
  18551. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18552. this._generatePointsArray();
  18553. if (!this._positions) {
  18554. return this;
  18555. }
  18556. // Transformation
  18557. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18558. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18559. subMesh._lastColliderWorldVertices = [];
  18560. subMesh._trianglePlanes = [];
  18561. var start = subMesh.verticesStart;
  18562. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18563. for (var i = start; i < end; i++) {
  18564. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18565. }
  18566. }
  18567. // Collide
  18568. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18569. if (collider.collisionFound) {
  18570. collider.collidedMesh = this;
  18571. }
  18572. return this;
  18573. };
  18574. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18575. var subMeshes;
  18576. var len;
  18577. // Octrees
  18578. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18579. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18580. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18581. len = intersections.length;
  18582. subMeshes = intersections.data;
  18583. }
  18584. else {
  18585. subMeshes = this.subMeshes;
  18586. len = subMeshes.length;
  18587. }
  18588. for (var index = 0; index < len; index++) {
  18589. var subMesh = subMeshes[index];
  18590. // Bounding test
  18591. if (len > 1 && !subMesh._checkCollision(collider))
  18592. continue;
  18593. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18594. }
  18595. return this;
  18596. };
  18597. AbstractMesh.prototype._checkCollision = function (collider) {
  18598. // Bounding box test
  18599. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18600. return this;
  18601. // Transformation matrix
  18602. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18603. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18604. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18605. return this;
  18606. };
  18607. // Picking
  18608. AbstractMesh.prototype._generatePointsArray = function () {
  18609. return false;
  18610. };
  18611. /**
  18612. * Checks if the passed Ray intersects with the mesh.
  18613. * Returns an object PickingInfo.
  18614. */
  18615. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18616. var pickingInfo = new BABYLON.PickingInfo();
  18617. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18618. return pickingInfo;
  18619. }
  18620. if (!this._generatePointsArray()) {
  18621. return pickingInfo;
  18622. }
  18623. var intersectInfo = null;
  18624. // Octrees
  18625. var subMeshes;
  18626. var len;
  18627. if (this._submeshesOctree && this.useOctreeForPicking) {
  18628. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18629. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18630. len = intersections.length;
  18631. subMeshes = intersections.data;
  18632. }
  18633. else {
  18634. subMeshes = this.subMeshes;
  18635. len = subMeshes.length;
  18636. }
  18637. for (var index = 0; index < len; index++) {
  18638. var subMesh = subMeshes[index];
  18639. // Bounding test
  18640. if (len > 1 && !subMesh.canIntersects(ray))
  18641. continue;
  18642. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18643. if (currentIntersectInfo) {
  18644. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18645. intersectInfo = currentIntersectInfo;
  18646. intersectInfo.subMeshId = index;
  18647. if (fastCheck) {
  18648. break;
  18649. }
  18650. }
  18651. }
  18652. }
  18653. if (intersectInfo) {
  18654. // Get picked point
  18655. var world = this.getWorldMatrix();
  18656. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18657. var direction = ray.direction.clone();
  18658. direction = direction.scale(intersectInfo.distance);
  18659. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18660. var pickedPoint = worldOrigin.add(worldDirection);
  18661. // Return result
  18662. pickingInfo.hit = true;
  18663. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18664. pickingInfo.pickedPoint = pickedPoint;
  18665. pickingInfo.pickedMesh = this;
  18666. pickingInfo.bu = intersectInfo.bu || 0;
  18667. pickingInfo.bv = intersectInfo.bv || 0;
  18668. pickingInfo.faceId = intersectInfo.faceId;
  18669. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18670. return pickingInfo;
  18671. }
  18672. return pickingInfo;
  18673. };
  18674. /**
  18675. * Clones the mesh, used by the class Mesh.
  18676. * Just returns `null` for an AbstractMesh.
  18677. */
  18678. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18679. return null;
  18680. };
  18681. /**
  18682. * Disposes all the mesh submeshes.
  18683. * Returns the AbstractMesh.
  18684. */
  18685. AbstractMesh.prototype.releaseSubMeshes = function () {
  18686. if (this.subMeshes) {
  18687. while (this.subMeshes.length) {
  18688. this.subMeshes[0].dispose();
  18689. }
  18690. }
  18691. else {
  18692. this.subMeshes = new Array();
  18693. }
  18694. return this;
  18695. };
  18696. /**
  18697. * Releases resources associated with this abstract mesh.
  18698. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18699. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18700. */
  18701. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18702. var _this = this;
  18703. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18704. var index;
  18705. // Smart Array Retainers.
  18706. this.getScene().freeActiveMeshes();
  18707. this.getScene().freeRenderingGroups();
  18708. // Action manager
  18709. if (this.actionManager !== undefined && this.actionManager !== null) {
  18710. this.actionManager.dispose();
  18711. this.actionManager = null;
  18712. }
  18713. // Skeleton
  18714. this._skeleton = null;
  18715. // Physics
  18716. if (this.physicsImpostor) {
  18717. this.physicsImpostor.dispose();
  18718. }
  18719. // Intersections in progress
  18720. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18721. var other = this._intersectionsInProgress[index];
  18722. var pos = other._intersectionsInProgress.indexOf(this);
  18723. other._intersectionsInProgress.splice(pos, 1);
  18724. }
  18725. this._intersectionsInProgress = [];
  18726. // Lights
  18727. var lights = this.getScene().lights;
  18728. lights.forEach(function (light) {
  18729. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18730. if (meshIndex !== -1) {
  18731. light.includedOnlyMeshes.splice(meshIndex, 1);
  18732. }
  18733. meshIndex = light.excludedMeshes.indexOf(_this);
  18734. if (meshIndex !== -1) {
  18735. light.excludedMeshes.splice(meshIndex, 1);
  18736. }
  18737. // Shadow generators
  18738. var generator = light.getShadowGenerator();
  18739. if (generator) {
  18740. var shadowMap = generator.getShadowMap();
  18741. if (shadowMap && shadowMap.renderList) {
  18742. meshIndex = shadowMap.renderList.indexOf(_this);
  18743. if (meshIndex !== -1) {
  18744. shadowMap.renderList.splice(meshIndex, 1);
  18745. }
  18746. }
  18747. }
  18748. });
  18749. // Edges
  18750. if (this._edgesRenderer) {
  18751. this._edgesRenderer.dispose();
  18752. this._edgesRenderer = null;
  18753. }
  18754. // SubMeshes
  18755. if (this.getClassName() !== "InstancedMesh") {
  18756. this.releaseSubMeshes();
  18757. }
  18758. // Octree
  18759. var sceneOctree = this.getScene().selectionOctree;
  18760. if (sceneOctree !== undefined && sceneOctree !== null) {
  18761. var index = sceneOctree.dynamicContent.indexOf(this);
  18762. if (index !== -1) {
  18763. sceneOctree.dynamicContent.splice(index, 1);
  18764. }
  18765. }
  18766. // Query
  18767. var engine = this.getScene().getEngine();
  18768. if (this._occlusionQuery) {
  18769. this._isOcclusionQueryInProgress = false;
  18770. engine.deleteQuery(this._occlusionQuery);
  18771. this._occlusionQuery = null;
  18772. }
  18773. // Engine
  18774. engine.wipeCaches();
  18775. // Remove from scene
  18776. this.getScene().removeMesh(this);
  18777. if (disposeMaterialAndTextures) {
  18778. if (this.material) {
  18779. this.material.dispose(false, true);
  18780. }
  18781. }
  18782. if (!doNotRecurse) {
  18783. // Particles
  18784. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18785. if (this.getScene().particleSystems[index].emitter === this) {
  18786. this.getScene().particleSystems[index].dispose();
  18787. index--;
  18788. }
  18789. }
  18790. }
  18791. // facet data
  18792. if (this._facetDataEnabled) {
  18793. this.disableFacetData();
  18794. }
  18795. this.onAfterWorldMatrixUpdateObservable.clear();
  18796. this.onCollideObservable.clear();
  18797. this.onCollisionPositionChangeObservable.clear();
  18798. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18799. };
  18800. /**
  18801. * Adds the passed mesh as a child to the current mesh.
  18802. * Returns the AbstractMesh.
  18803. */
  18804. AbstractMesh.prototype.addChild = function (mesh) {
  18805. mesh.setParent(this);
  18806. return this;
  18807. };
  18808. /**
  18809. * Removes the passed mesh from the current mesh children list.
  18810. * Returns the AbstractMesh.
  18811. */
  18812. AbstractMesh.prototype.removeChild = function (mesh) {
  18813. mesh.setParent(null);
  18814. return this;
  18815. };
  18816. // Facet data
  18817. /**
  18818. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18819. * Returns the AbstractMesh.
  18820. */
  18821. AbstractMesh.prototype._initFacetData = function () {
  18822. if (!this._facetNormals) {
  18823. this._facetNormals = new Array();
  18824. }
  18825. if (!this._facetPositions) {
  18826. this._facetPositions = new Array();
  18827. }
  18828. if (!this._facetPartitioning) {
  18829. this._facetPartitioning = new Array();
  18830. }
  18831. this._facetNb = (this.getIndices().length / 3) | 0;
  18832. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18833. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18834. for (var f = 0; f < this._facetNb; f++) {
  18835. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18836. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18837. }
  18838. this._facetDataEnabled = true;
  18839. return this;
  18840. };
  18841. /**
  18842. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18843. * This method can be called within the render loop.
  18844. * 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.
  18845. * Returns the AbstractMesh.
  18846. */
  18847. AbstractMesh.prototype.updateFacetData = function () {
  18848. if (!this._facetDataEnabled) {
  18849. this._initFacetData();
  18850. }
  18851. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18852. var indices = this.getIndices();
  18853. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18854. var bInfo = this.getBoundingInfo();
  18855. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18856. // init arrays, matrix and sort function on first call
  18857. this._facetDepthSortEnabled = true;
  18858. if (indices instanceof Uint16Array) {
  18859. this._depthSortedIndices = new Uint16Array(indices);
  18860. }
  18861. else if (indices instanceof Uint32Array) {
  18862. this._depthSortedIndices = new Uint32Array(indices);
  18863. }
  18864. else {
  18865. var needs32bits = false;
  18866. for (var i = 0; i < indices.length; i++) {
  18867. if (indices[i] > 65535) {
  18868. needs32bits = true;
  18869. break;
  18870. }
  18871. }
  18872. if (needs32bits) {
  18873. this._depthSortedIndices = new Uint32Array(indices);
  18874. }
  18875. else {
  18876. this._depthSortedIndices = new Uint16Array(indices);
  18877. }
  18878. }
  18879. this._facetDepthSortFunction = function (f1, f2) {
  18880. return (f2.sqDistance - f1.sqDistance);
  18881. };
  18882. if (!this._facetDepthSortFrom) {
  18883. var camera = this.getScene().activeCamera;
  18884. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18885. }
  18886. this._depthSortedFacets = [];
  18887. for (var f = 0; f < this._facetNb; f++) {
  18888. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18889. this._depthSortedFacets.push(depthSortedFacet);
  18890. }
  18891. this._invertedMatrix = BABYLON.Matrix.Identity();
  18892. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18893. }
  18894. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18895. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18896. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18897. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18898. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18899. this._subDiv.max = this._partitioningSubdivisions;
  18900. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18901. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18902. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18903. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18904. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18905. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18906. // set the parameters for ComputeNormals()
  18907. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18908. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18909. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18910. this._facetParameters.bInfo = bInfo;
  18911. this._facetParameters.bbSize = this._bbSize;
  18912. this._facetParameters.subDiv = this._subDiv;
  18913. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18914. this._facetParameters.depthSort = this._facetDepthSort;
  18915. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18916. this.computeWorldMatrix(true);
  18917. this._worldMatrix.invertToRef(this._invertedMatrix);
  18918. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18919. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18920. }
  18921. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18922. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18923. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18924. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18925. var l = (this._depthSortedIndices.length / 3) | 0;
  18926. for (var f = 0; f < l; f++) {
  18927. var sind = this._depthSortedFacets[f].ind;
  18928. this._depthSortedIndices[f * 3] = indices[sind];
  18929. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18930. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18931. }
  18932. this.updateIndices(this._depthSortedIndices);
  18933. }
  18934. return this;
  18935. };
  18936. /**
  18937. * Returns the facetLocalNormals array.
  18938. * The normals are expressed in the mesh local space.
  18939. */
  18940. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18941. if (!this._facetNormals) {
  18942. this.updateFacetData();
  18943. }
  18944. return this._facetNormals;
  18945. };
  18946. /**
  18947. * Returns the facetLocalPositions array.
  18948. * The facet positions are expressed in the mesh local space.
  18949. */
  18950. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18951. if (!this._facetPositions) {
  18952. this.updateFacetData();
  18953. }
  18954. return this._facetPositions;
  18955. };
  18956. /**
  18957. * Returns the facetLocalPartioning array.
  18958. */
  18959. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18960. if (!this._facetPartitioning) {
  18961. this.updateFacetData();
  18962. }
  18963. return this._facetPartitioning;
  18964. };
  18965. /**
  18966. * Returns the i-th facet position in the world system.
  18967. * This method allocates a new Vector3 per call.
  18968. */
  18969. AbstractMesh.prototype.getFacetPosition = function (i) {
  18970. var pos = BABYLON.Vector3.Zero();
  18971. this.getFacetPositionToRef(i, pos);
  18972. return pos;
  18973. };
  18974. /**
  18975. * Sets the reference Vector3 with the i-th facet position in the world system.
  18976. * Returns the AbstractMesh.
  18977. */
  18978. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18979. var localPos = (this.getFacetLocalPositions())[i];
  18980. var world = this.getWorldMatrix();
  18981. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18982. return this;
  18983. };
  18984. /**
  18985. * Returns the i-th facet normal in the world system.
  18986. * This method allocates a new Vector3 per call.
  18987. */
  18988. AbstractMesh.prototype.getFacetNormal = function (i) {
  18989. var norm = BABYLON.Vector3.Zero();
  18990. this.getFacetNormalToRef(i, norm);
  18991. return norm;
  18992. };
  18993. /**
  18994. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18995. * Returns the AbstractMesh.
  18996. */
  18997. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18998. var localNorm = (this.getFacetLocalNormals())[i];
  18999. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19000. return this;
  19001. };
  19002. /**
  19003. * 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).
  19004. */
  19005. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19006. var bInfo = this.getBoundingInfo();
  19007. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19008. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19009. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19010. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19011. return null;
  19012. }
  19013. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19014. };
  19015. /**
  19016. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19017. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19018. * 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.
  19019. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19020. * 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.
  19021. */
  19022. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19023. if (checkFace === void 0) { checkFace = false; }
  19024. if (facing === void 0) { facing = true; }
  19025. var world = this.getWorldMatrix();
  19026. var invMat = BABYLON.Tmp.Matrix[5];
  19027. world.invertToRef(invMat);
  19028. var invVect = BABYLON.Tmp.Vector3[8];
  19029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19030. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19031. if (projected) {
  19032. // tranform the local computed projected vector to world coordinates
  19033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19034. }
  19035. return closest;
  19036. };
  19037. /**
  19038. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19039. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19040. * 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.
  19041. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19042. * 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.
  19043. */
  19044. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19045. if (checkFace === void 0) { checkFace = false; }
  19046. if (facing === void 0) { facing = true; }
  19047. var closest = null;
  19048. var tmpx = 0.0;
  19049. var tmpy = 0.0;
  19050. var tmpz = 0.0;
  19051. var d = 0.0; // tmp dot facet normal * facet position
  19052. var t0 = 0.0;
  19053. var projx = 0.0;
  19054. var projy = 0.0;
  19055. var projz = 0.0;
  19056. // Get all the facets in the same partitioning block than (x, y, z)
  19057. var facetPositions = this.getFacetLocalPositions();
  19058. var facetNormals = this.getFacetLocalNormals();
  19059. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19060. if (!facetsInBlock) {
  19061. return null;
  19062. }
  19063. // Get the closest facet to (x, y, z)
  19064. var shortest = Number.MAX_VALUE; // init distance vars
  19065. var tmpDistance = shortest;
  19066. var fib; // current facet in the block
  19067. var norm; // current facet normal
  19068. var p0; // current facet barycenter position
  19069. // loop on all the facets in the current partitioning block
  19070. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19071. fib = facetsInBlock[idx];
  19072. norm = facetNormals[fib];
  19073. p0 = facetPositions[fib];
  19074. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19075. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19076. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19077. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19078. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19079. projx = x + norm.x * t0;
  19080. projy = y + norm.y * t0;
  19081. projz = z + norm.z * t0;
  19082. tmpx = projx - x;
  19083. tmpy = projy - y;
  19084. tmpz = projz - z;
  19085. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19086. if (tmpDistance < shortest) {
  19087. shortest = tmpDistance;
  19088. closest = fib;
  19089. if (projected) {
  19090. projected.x = projx;
  19091. projected.y = projy;
  19092. projected.z = projz;
  19093. }
  19094. }
  19095. }
  19096. }
  19097. return closest;
  19098. };
  19099. /**
  19100. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19101. */
  19102. AbstractMesh.prototype.getFacetDataParameters = function () {
  19103. return this._facetParameters;
  19104. };
  19105. /**
  19106. * Disables the feature FacetData and frees the related memory.
  19107. * Returns the AbstractMesh.
  19108. */
  19109. AbstractMesh.prototype.disableFacetData = function () {
  19110. if (this._facetDataEnabled) {
  19111. this._facetDataEnabled = false;
  19112. this._facetPositions = new Array();
  19113. this._facetNormals = new Array();
  19114. this._facetPartitioning = new Array();
  19115. this._facetParameters = null;
  19116. this._depthSortedIndices = new Uint32Array(0);
  19117. }
  19118. return this;
  19119. };
  19120. /**
  19121. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19122. * Returns the mesh.
  19123. */
  19124. AbstractMesh.prototype.updateIndices = function (indices) {
  19125. return this;
  19126. };
  19127. /**
  19128. * The mesh Geometry. Actually used by the Mesh object.
  19129. * Returns a blank geometry object.
  19130. */
  19131. /**
  19132. * Creates new normals data for the mesh.
  19133. * @param updatable.
  19134. */
  19135. AbstractMesh.prototype.createNormals = function (updatable) {
  19136. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19137. var indices = this.getIndices();
  19138. var normals;
  19139. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19140. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19141. }
  19142. else {
  19143. normals = [];
  19144. }
  19145. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19146. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19147. };
  19148. /**
  19149. * Align the mesh with a normal.
  19150. * Returns the mesh.
  19151. */
  19152. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19153. if (!upDirection) {
  19154. upDirection = BABYLON.Axis.Y;
  19155. }
  19156. var axisX = BABYLON.Tmp.Vector3[0];
  19157. var axisZ = BABYLON.Tmp.Vector3[1];
  19158. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19159. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19160. if (this.rotationQuaternion) {
  19161. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19162. }
  19163. else {
  19164. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19165. }
  19166. return this;
  19167. };
  19168. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19169. var engine = this.getEngine();
  19170. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19171. this._isOccluded = false;
  19172. return;
  19173. }
  19174. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19175. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19176. if (isOcclusionQueryAvailable) {
  19177. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19178. this._isOcclusionQueryInProgress = false;
  19179. this._occlusionInternalRetryCounter = 0;
  19180. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19181. }
  19182. else {
  19183. this._occlusionInternalRetryCounter++;
  19184. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19185. this._isOcclusionQueryInProgress = false;
  19186. this._occlusionInternalRetryCounter = 0;
  19187. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19188. // if strict continue the last state of the object.
  19189. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19190. }
  19191. else {
  19192. return;
  19193. }
  19194. }
  19195. }
  19196. var scene = this.getScene();
  19197. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19198. if (!this._occlusionQuery) {
  19199. this._occlusionQuery = engine.createQuery();
  19200. }
  19201. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19202. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19203. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19204. this._isOcclusionQueryInProgress = true;
  19205. };
  19206. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19207. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19208. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19209. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19210. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19211. return AbstractMesh;
  19212. }(BABYLON.TransformNode));
  19213. BABYLON.AbstractMesh = AbstractMesh;
  19214. })(BABYLON || (BABYLON = {}));
  19215. //# sourceMappingURL=babylon.abstractMesh.js.map
  19216. "use strict";
  19217. var BABYLON;
  19218. (function (BABYLON) {
  19219. /**
  19220. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19221. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19222. * 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.
  19223. */
  19224. var Light = /** @class */ (function (_super) {
  19225. __extends(Light, _super);
  19226. /**
  19227. * Creates a Light object in the scene.
  19228. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19229. * @param name The firendly name of the light
  19230. * @param scene The scene the light belongs too
  19231. */
  19232. function Light(name, scene) {
  19233. var _this = _super.call(this, name, scene) || this;
  19234. /**
  19235. * Diffuse gives the basic color to an object.
  19236. */
  19237. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19238. /**
  19239. * Specular produces a highlight color on an object.
  19240. * Note: This is note affecting PBR materials.
  19241. */
  19242. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19243. /**
  19244. * Strength of the light.
  19245. * Note: By default it is define in the framework own unit.
  19246. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19247. */
  19248. _this.intensity = 1.0;
  19249. /**
  19250. * Defines how far from the source the light is impacting in scene units.
  19251. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19252. */
  19253. _this.range = Number.MAX_VALUE;
  19254. /**
  19255. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19256. * of light.
  19257. */
  19258. _this._photometricScale = 1.0;
  19259. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19260. _this._radius = 0.00001;
  19261. /**
  19262. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19263. * exceeding the number allowed of the materials.
  19264. */
  19265. _this.renderPriority = 0;
  19266. /**
  19267. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19268. * the current shadow generator.
  19269. */
  19270. _this.shadowEnabled = true;
  19271. _this._excludeWithLayerMask = 0;
  19272. _this._includeOnlyWithLayerMask = 0;
  19273. _this._lightmapMode = 0;
  19274. /**
  19275. * @ignore Internal use only.
  19276. */
  19277. _this._excludedMeshesIds = new Array();
  19278. /**
  19279. * @ignore Internal use only.
  19280. */
  19281. _this._includedOnlyMeshesIds = new Array();
  19282. _this.getScene().addLight(_this);
  19283. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19284. _this._buildUniformLayout();
  19285. _this.includedOnlyMeshes = new Array();
  19286. _this.excludedMeshes = new Array();
  19287. _this._resyncMeshes();
  19288. return _this;
  19289. }
  19290. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19291. /**
  19292. * If every light affecting the material is in this lightmapMode,
  19293. * material.lightmapTexture adds or multiplies
  19294. * (depends on material.useLightmapAsShadowmap)
  19295. * after every other light calculations.
  19296. */
  19297. get: function () {
  19298. return Light._LIGHTMAP_DEFAULT;
  19299. },
  19300. enumerable: true,
  19301. configurable: true
  19302. });
  19303. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19304. /**
  19305. * material.lightmapTexture as only diffuse lighting from this light
  19306. * adds only specular lighting from this light
  19307. * adds dynamic shadows
  19308. */
  19309. get: function () {
  19310. return Light._LIGHTMAP_SPECULAR;
  19311. },
  19312. enumerable: true,
  19313. configurable: true
  19314. });
  19315. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19316. /**
  19317. * material.lightmapTexture as only lighting
  19318. * no light calculation from this light
  19319. * only adds dynamic shadows from this light
  19320. */
  19321. get: function () {
  19322. return Light._LIGHTMAP_SHADOWSONLY;
  19323. },
  19324. enumerable: true,
  19325. configurable: true
  19326. });
  19327. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19328. /**
  19329. * Each light type uses the default quantity according to its type:
  19330. * point/spot lights use luminous intensity
  19331. * directional lights use illuminance
  19332. */
  19333. get: function () {
  19334. return Light._INTENSITYMODE_AUTOMATIC;
  19335. },
  19336. enumerable: true,
  19337. configurable: true
  19338. });
  19339. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19340. /**
  19341. * lumen (lm)
  19342. */
  19343. get: function () {
  19344. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19345. },
  19346. enumerable: true,
  19347. configurable: true
  19348. });
  19349. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19350. /**
  19351. * candela (lm/sr)
  19352. */
  19353. get: function () {
  19354. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19360. /**
  19361. * lux (lm/m^2)
  19362. */
  19363. get: function () {
  19364. return Light._INTENSITYMODE_ILLUMINANCE;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19370. /**
  19371. * nit (cd/m^2)
  19372. */
  19373. get: function () {
  19374. return Light._INTENSITYMODE_LUMINANCE;
  19375. },
  19376. enumerable: true,
  19377. configurable: true
  19378. });
  19379. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19380. /**
  19381. * Light type const id of the point light.
  19382. */
  19383. get: function () {
  19384. return Light._LIGHTTYPEID_POINTLIGHT;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19390. /**
  19391. * Light type const id of the directional light.
  19392. */
  19393. get: function () {
  19394. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19400. /**
  19401. * Light type const id of the spot light.
  19402. */
  19403. get: function () {
  19404. return Light._LIGHTTYPEID_SPOTLIGHT;
  19405. },
  19406. enumerable: true,
  19407. configurable: true
  19408. });
  19409. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19410. /**
  19411. * Light type const id of the hemispheric light.
  19412. */
  19413. get: function () {
  19414. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19415. },
  19416. enumerable: true,
  19417. configurable: true
  19418. });
  19419. Object.defineProperty(Light.prototype, "intensityMode", {
  19420. /**
  19421. * Gets the photometric scale used to interpret the intensity.
  19422. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19423. */
  19424. get: function () {
  19425. return this._intensityMode;
  19426. },
  19427. /**
  19428. * Sets the photometric scale used to interpret the intensity.
  19429. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19430. */
  19431. set: function (value) {
  19432. this._intensityMode = value;
  19433. this._computePhotometricScale();
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. ;
  19439. ;
  19440. Object.defineProperty(Light.prototype, "radius", {
  19441. /**
  19442. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19443. */
  19444. get: function () {
  19445. return this._radius;
  19446. },
  19447. /**
  19448. * sets the light radius used by PBR Materials to simulate soft area lights.
  19449. */
  19450. set: function (value) {
  19451. this._radius = value;
  19452. this._computePhotometricScale();
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. ;
  19458. ;
  19459. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19460. /**
  19461. * Gets the only meshes impacted by this light.
  19462. */
  19463. get: function () {
  19464. return this._includedOnlyMeshes;
  19465. },
  19466. /**
  19467. * Sets the only meshes impacted by this light.
  19468. */
  19469. set: function (value) {
  19470. this._includedOnlyMeshes = value;
  19471. this._hookArrayForIncludedOnly(value);
  19472. },
  19473. enumerable: true,
  19474. configurable: true
  19475. });
  19476. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19477. /**
  19478. * Gets the meshes not impacted by this light.
  19479. */
  19480. get: function () {
  19481. return this._excludedMeshes;
  19482. },
  19483. /**
  19484. * Sets the meshes not impacted by this light.
  19485. */
  19486. set: function (value) {
  19487. this._excludedMeshes = value;
  19488. this._hookArrayForExcluded(value);
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19494. /**
  19495. * Gets the layer id use to find what meshes are not impacted by the light.
  19496. * Inactive if 0
  19497. */
  19498. get: function () {
  19499. return this._excludeWithLayerMask;
  19500. },
  19501. /**
  19502. * Sets the layer id use to find what meshes are not impacted by the light.
  19503. * Inactive if 0
  19504. */
  19505. set: function (value) {
  19506. this._excludeWithLayerMask = value;
  19507. this._resyncMeshes();
  19508. },
  19509. enumerable: true,
  19510. configurable: true
  19511. });
  19512. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19513. /**
  19514. * Gets the layer id use to find what meshes are impacted by the light.
  19515. * Inactive if 0
  19516. */
  19517. get: function () {
  19518. return this._includeOnlyWithLayerMask;
  19519. },
  19520. /**
  19521. * Sets the layer id use to find what meshes are impacted by the light.
  19522. * Inactive if 0
  19523. */
  19524. set: function (value) {
  19525. this._includeOnlyWithLayerMask = value;
  19526. this._resyncMeshes();
  19527. },
  19528. enumerable: true,
  19529. configurable: true
  19530. });
  19531. Object.defineProperty(Light.prototype, "lightmapMode", {
  19532. /**
  19533. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19534. */
  19535. get: function () {
  19536. return this._lightmapMode;
  19537. },
  19538. /**
  19539. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19540. */
  19541. set: function (value) {
  19542. if (this._lightmapMode === value) {
  19543. return;
  19544. }
  19545. this._lightmapMode = value;
  19546. this._markMeshesAsLightDirty();
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. /**
  19552. * Returns the string "Light".
  19553. * @returns the class name
  19554. */
  19555. Light.prototype.getClassName = function () {
  19556. return "Light";
  19557. };
  19558. /**
  19559. * Converts the light information to a readable string for debug purpose.
  19560. * @param fullDetails Supports for multiple levels of logging within scene loading
  19561. * @returns the human readable light info
  19562. */
  19563. Light.prototype.toString = function (fullDetails) {
  19564. var ret = "Name: " + this.name;
  19565. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19566. if (this.animations) {
  19567. for (var i = 0; i < this.animations.length; i++) {
  19568. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19569. }
  19570. }
  19571. if (fullDetails) {
  19572. }
  19573. return ret;
  19574. };
  19575. /**
  19576. * Set the enabled state of this node.
  19577. * @param value - the new enabled state
  19578. */
  19579. Light.prototype.setEnabled = function (value) {
  19580. _super.prototype.setEnabled.call(this, value);
  19581. this._resyncMeshes();
  19582. };
  19583. /**
  19584. * Returns the Light associated shadow generator if any.
  19585. * @return the associated shadow generator.
  19586. */
  19587. Light.prototype.getShadowGenerator = function () {
  19588. return this._shadowGenerator;
  19589. };
  19590. /**
  19591. * Returns a Vector3, the absolute light position in the World.
  19592. * @returns the world space position of the light
  19593. */
  19594. Light.prototype.getAbsolutePosition = function () {
  19595. return BABYLON.Vector3.Zero();
  19596. };
  19597. /**
  19598. * Specifies if the light will affect the passed mesh.
  19599. * @param mesh The mesh to test against the light
  19600. * @return true the mesh is affected otherwise, false.
  19601. */
  19602. Light.prototype.canAffectMesh = function (mesh) {
  19603. if (!mesh) {
  19604. return true;
  19605. }
  19606. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19607. return false;
  19608. }
  19609. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19610. return false;
  19611. }
  19612. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19613. return false;
  19614. }
  19615. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19616. return false;
  19617. }
  19618. return true;
  19619. };
  19620. /**
  19621. * Computes and Returns the light World matrix.
  19622. * @returns the world matrix
  19623. */
  19624. Light.prototype.getWorldMatrix = function () {
  19625. this._currentRenderId = this.getScene().getRenderId();
  19626. this._childRenderId = this._currentRenderId;
  19627. var worldMatrix = this._getWorldMatrix();
  19628. if (this.parent && this.parent.getWorldMatrix) {
  19629. if (!this._parentedWorldMatrix) {
  19630. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19631. }
  19632. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19633. this._markSyncedWithParent();
  19634. return this._parentedWorldMatrix;
  19635. }
  19636. return worldMatrix;
  19637. };
  19638. /**
  19639. * Sort function to order lights for rendering.
  19640. * @param a First Light object to compare to second.
  19641. * @param b Second Light object to compare first.
  19642. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19643. */
  19644. Light.CompareLightsPriority = function (a, b) {
  19645. //shadow-casting lights have priority over non-shadow-casting lights
  19646. //the renderPrioirty is a secondary sort criterion
  19647. if (a.shadowEnabled !== b.shadowEnabled) {
  19648. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19649. }
  19650. return b.renderPriority - a.renderPriority;
  19651. };
  19652. /**
  19653. * Releases resources associated with this node.
  19654. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19655. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19656. */
  19657. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19658. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19659. if (this._shadowGenerator) {
  19660. this._shadowGenerator.dispose();
  19661. this._shadowGenerator = null;
  19662. }
  19663. // Animations
  19664. this.getScene().stopAnimation(this);
  19665. // Remove from meshes
  19666. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19667. var mesh = _a[_i];
  19668. mesh._removeLightSource(this);
  19669. }
  19670. this._uniformBuffer.dispose();
  19671. // Remove from scene
  19672. this.getScene().removeLight(this);
  19673. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19674. };
  19675. /**
  19676. * Returns the light type ID (integer).
  19677. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19678. */
  19679. Light.prototype.getTypeID = function () {
  19680. return 0;
  19681. };
  19682. /**
  19683. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19684. * @returns the scaled intensity in intensity mode unit
  19685. */
  19686. Light.prototype.getScaledIntensity = function () {
  19687. return this._photometricScale * this.intensity;
  19688. };
  19689. /**
  19690. * Returns a new Light object, named "name", from the current one.
  19691. * @param name The name of the cloned light
  19692. * @returns the new created light
  19693. */
  19694. Light.prototype.clone = function (name) {
  19695. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19696. if (!constructor) {
  19697. return null;
  19698. }
  19699. return BABYLON.SerializationHelper.Clone(constructor, this);
  19700. };
  19701. /**
  19702. * Serializes the current light into a Serialization object.
  19703. * @returns the serialized object.
  19704. */
  19705. Light.prototype.serialize = function () {
  19706. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19707. // Type
  19708. serializationObject.type = this.getTypeID();
  19709. // Parent
  19710. if (this.parent) {
  19711. serializationObject.parentId = this.parent.id;
  19712. }
  19713. // Inclusion / exclusions
  19714. if (this.excludedMeshes.length > 0) {
  19715. serializationObject.excludedMeshesIds = [];
  19716. this.excludedMeshes.forEach(function (mesh) {
  19717. serializationObject.excludedMeshesIds.push(mesh.id);
  19718. });
  19719. }
  19720. if (this.includedOnlyMeshes.length > 0) {
  19721. serializationObject.includedOnlyMeshesIds = [];
  19722. this.includedOnlyMeshes.forEach(function (mesh) {
  19723. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19724. });
  19725. }
  19726. // Animations
  19727. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19728. serializationObject.ranges = this.serializeAnimationRanges();
  19729. return serializationObject;
  19730. };
  19731. /**
  19732. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19733. * This new light is named "name" and added to the passed scene.
  19734. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19735. * @param name The friendly name of the light
  19736. * @param scene The scene the new light will belong to
  19737. * @returns the constructor function
  19738. */
  19739. Light.GetConstructorFromName = function (type, name, scene) {
  19740. switch (type) {
  19741. case 0:
  19742. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19743. case 1:
  19744. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19745. case 2:
  19746. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19747. case 3:
  19748. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19749. }
  19750. return null;
  19751. };
  19752. /**
  19753. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19754. * @param parsedLight The JSON representation of the light
  19755. * @param scene The scene to create the parsed light in
  19756. * @returns the created light after parsing
  19757. */
  19758. Light.Parse = function (parsedLight, scene) {
  19759. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19760. if (!constructor) {
  19761. return null;
  19762. }
  19763. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19764. // Inclusion / exclusions
  19765. if (parsedLight.excludedMeshesIds) {
  19766. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19767. }
  19768. if (parsedLight.includedOnlyMeshesIds) {
  19769. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19770. }
  19771. // Parent
  19772. if (parsedLight.parentId) {
  19773. light._waitingParentId = parsedLight.parentId;
  19774. }
  19775. // Animations
  19776. if (parsedLight.animations) {
  19777. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19778. var parsedAnimation = parsedLight.animations[animationIndex];
  19779. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19780. }
  19781. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19782. }
  19783. if (parsedLight.autoAnimate) {
  19784. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19785. }
  19786. return light;
  19787. };
  19788. Light.prototype._hookArrayForExcluded = function (array) {
  19789. var _this = this;
  19790. var oldPush = array.push;
  19791. array.push = function () {
  19792. var items = [];
  19793. for (var _i = 0; _i < arguments.length; _i++) {
  19794. items[_i] = arguments[_i];
  19795. }
  19796. var result = oldPush.apply(array, items);
  19797. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19798. var item = items_1[_a];
  19799. item._resyncLighSource(_this);
  19800. }
  19801. return result;
  19802. };
  19803. var oldSplice = array.splice;
  19804. array.splice = function (index, deleteCount) {
  19805. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19806. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19807. var item = deleted_1[_i];
  19808. item._resyncLighSource(_this);
  19809. }
  19810. return deleted;
  19811. };
  19812. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19813. var item = array_1[_i];
  19814. item._resyncLighSource(this);
  19815. }
  19816. };
  19817. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19818. var _this = this;
  19819. var oldPush = array.push;
  19820. array.push = function () {
  19821. var items = [];
  19822. for (var _i = 0; _i < arguments.length; _i++) {
  19823. items[_i] = arguments[_i];
  19824. }
  19825. var result = oldPush.apply(array, items);
  19826. _this._resyncMeshes();
  19827. return result;
  19828. };
  19829. var oldSplice = array.splice;
  19830. array.splice = function (index, deleteCount) {
  19831. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19832. _this._resyncMeshes();
  19833. return deleted;
  19834. };
  19835. this._resyncMeshes();
  19836. };
  19837. Light.prototype._resyncMeshes = function () {
  19838. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19839. var mesh = _a[_i];
  19840. mesh._resyncLighSource(this);
  19841. }
  19842. };
  19843. /**
  19844. * Forces the meshes to update their light related information in their rendering used effects
  19845. * @ignore Internal Use Only
  19846. */
  19847. Light.prototype._markMeshesAsLightDirty = function () {
  19848. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19849. var mesh = _a[_i];
  19850. if (mesh._lightSources.indexOf(this) !== -1) {
  19851. mesh._markSubMeshesAsLightDirty();
  19852. }
  19853. }
  19854. };
  19855. /**
  19856. * Recomputes the cached photometric scale if needed.
  19857. */
  19858. Light.prototype._computePhotometricScale = function () {
  19859. this._photometricScale = this._getPhotometricScale();
  19860. this.getScene().resetCachedMaterial();
  19861. };
  19862. /**
  19863. * Returns the Photometric Scale according to the light type and intensity mode.
  19864. */
  19865. Light.prototype._getPhotometricScale = function () {
  19866. var photometricScale = 0.0;
  19867. var lightTypeID = this.getTypeID();
  19868. //get photometric mode
  19869. var photometricMode = this.intensityMode;
  19870. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19871. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19872. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19873. }
  19874. else {
  19875. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19876. }
  19877. }
  19878. //compute photometric scale
  19879. switch (lightTypeID) {
  19880. case Light.LIGHTTYPEID_POINTLIGHT:
  19881. case Light.LIGHTTYPEID_SPOTLIGHT:
  19882. switch (photometricMode) {
  19883. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19884. photometricScale = 1.0 / (4.0 * Math.PI);
  19885. break;
  19886. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19887. photometricScale = 1.0;
  19888. break;
  19889. case Light.INTENSITYMODE_LUMINANCE:
  19890. photometricScale = this.radius * this.radius;
  19891. break;
  19892. }
  19893. break;
  19894. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19895. switch (photometricMode) {
  19896. case Light.INTENSITYMODE_ILLUMINANCE:
  19897. photometricScale = 1.0;
  19898. break;
  19899. case Light.INTENSITYMODE_LUMINANCE:
  19900. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19901. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19902. var apexAngleRadians = this.radius;
  19903. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19904. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19905. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19906. photometricScale = solidAngle;
  19907. break;
  19908. }
  19909. break;
  19910. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19911. // No fall off in hemisperic light.
  19912. photometricScale = 1.0;
  19913. break;
  19914. }
  19915. return photometricScale;
  19916. };
  19917. /**
  19918. * Reorder the light in the scene according to their defined priority.
  19919. * @ignore Internal Use Only
  19920. */
  19921. Light.prototype._reorderLightsInScene = function () {
  19922. var scene = this.getScene();
  19923. if (this._renderPriority != 0) {
  19924. scene.requireLightSorting = true;
  19925. }
  19926. this.getScene().sortLightsByPriority();
  19927. };
  19928. //lightmapMode Consts
  19929. Light._LIGHTMAP_DEFAULT = 0;
  19930. Light._LIGHTMAP_SPECULAR = 1;
  19931. Light._LIGHTMAP_SHADOWSONLY = 2;
  19932. // Intensity Mode Consts
  19933. Light._INTENSITYMODE_AUTOMATIC = 0;
  19934. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19935. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19936. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19937. Light._INTENSITYMODE_LUMINANCE = 4;
  19938. // Light types ids const.
  19939. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19940. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19941. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19942. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19943. __decorate([
  19944. BABYLON.serializeAsColor3()
  19945. ], Light.prototype, "diffuse", void 0);
  19946. __decorate([
  19947. BABYLON.serializeAsColor3()
  19948. ], Light.prototype, "specular", void 0);
  19949. __decorate([
  19950. BABYLON.serialize()
  19951. ], Light.prototype, "intensity", void 0);
  19952. __decorate([
  19953. BABYLON.serialize()
  19954. ], Light.prototype, "range", void 0);
  19955. __decorate([
  19956. BABYLON.serialize()
  19957. ], Light.prototype, "intensityMode", null);
  19958. __decorate([
  19959. BABYLON.serialize()
  19960. ], Light.prototype, "radius", null);
  19961. __decorate([
  19962. BABYLON.serialize()
  19963. ], Light.prototype, "_renderPriority", void 0);
  19964. __decorate([
  19965. BABYLON.expandToProperty("_reorderLightsInScene")
  19966. ], Light.prototype, "renderPriority", void 0);
  19967. __decorate([
  19968. BABYLON.serialize()
  19969. ], Light.prototype, "shadowEnabled", void 0);
  19970. __decorate([
  19971. BABYLON.serialize("excludeWithLayerMask")
  19972. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19973. __decorate([
  19974. BABYLON.serialize("includeOnlyWithLayerMask")
  19975. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19976. __decorate([
  19977. BABYLON.serialize("lightmapMode")
  19978. ], Light.prototype, "_lightmapMode", void 0);
  19979. return Light;
  19980. }(BABYLON.Node));
  19981. BABYLON.Light = Light;
  19982. })(BABYLON || (BABYLON = {}));
  19983. //# sourceMappingURL=babylon.light.js.map
  19984. "use strict";
  19985. var BABYLON;
  19986. (function (BABYLON) {
  19987. var Camera = /** @class */ (function (_super) {
  19988. __extends(Camera, _super);
  19989. function Camera(name, position, scene) {
  19990. var _this = _super.call(this, name, scene) || this;
  19991. /**
  19992. * The vector the camera should consider as up.
  19993. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19994. */
  19995. _this.upVector = BABYLON.Vector3.Up();
  19996. _this.orthoLeft = null;
  19997. _this.orthoRight = null;
  19998. _this.orthoBottom = null;
  19999. _this.orthoTop = null;
  20000. /**
  20001. * FOV is set in Radians. (default is 0.8)
  20002. */
  20003. _this.fov = 0.8;
  20004. _this.minZ = 1;
  20005. _this.maxZ = 10000.0;
  20006. _this.inertia = 0.9;
  20007. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20008. _this.isIntermediate = false;
  20009. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20010. /**
  20011. * Restricts the camera to viewing objects with the same layerMask.
  20012. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20013. */
  20014. _this.layerMask = 0x0FFFFFFF;
  20015. /**
  20016. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20017. */
  20018. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20019. // Camera rig members
  20020. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20021. _this._rigCameras = new Array();
  20022. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20023. _this._skipRendering = false;
  20024. _this.customRenderTargets = new Array();
  20025. // Observables
  20026. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20027. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20028. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20029. _this.onRestoreStateObservable = new BABYLON.Observable();
  20030. // Cache
  20031. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20032. _this._projectionMatrix = new BABYLON.Matrix();
  20033. _this._doNotComputeProjectionMatrix = false;
  20034. _this._postProcesses = new Array();
  20035. _this._transformMatrix = BABYLON.Matrix.Zero();
  20036. _this._activeMeshes = new BABYLON.SmartArray(256);
  20037. _this._globalPosition = BABYLON.Vector3.Zero();
  20038. _this._refreshFrustumPlanes = true;
  20039. _this.getScene().addCamera(_this);
  20040. if (!_this.getScene().activeCamera) {
  20041. _this.getScene().activeCamera = _this;
  20042. }
  20043. _this.position = position;
  20044. return _this;
  20045. }
  20046. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20047. get: function () {
  20048. return Camera._PERSPECTIVE_CAMERA;
  20049. },
  20050. enumerable: true,
  20051. configurable: true
  20052. });
  20053. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20054. get: function () {
  20055. return Camera._ORTHOGRAPHIC_CAMERA;
  20056. },
  20057. enumerable: true,
  20058. configurable: true
  20059. });
  20060. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20061. /**
  20062. * This is the default FOV mode for perspective cameras.
  20063. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20064. *
  20065. */
  20066. get: function () {
  20067. return Camera._FOVMODE_VERTICAL_FIXED;
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20073. /**
  20074. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20075. *
  20076. */
  20077. get: function () {
  20078. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20079. },
  20080. enumerable: true,
  20081. configurable: true
  20082. });
  20083. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20084. get: function () {
  20085. return Camera._RIG_MODE_NONE;
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20091. get: function () {
  20092. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20093. },
  20094. enumerable: true,
  20095. configurable: true
  20096. });
  20097. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20098. get: function () {
  20099. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20100. },
  20101. enumerable: true,
  20102. configurable: true
  20103. });
  20104. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20105. get: function () {
  20106. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20112. get: function () {
  20113. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20119. get: function () {
  20120. return Camera._RIG_MODE_VR;
  20121. },
  20122. enumerable: true,
  20123. configurable: true
  20124. });
  20125. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20126. get: function () {
  20127. return Camera._RIG_MODE_WEBVR;
  20128. },
  20129. enumerable: true,
  20130. configurable: true
  20131. });
  20132. /**
  20133. * Store current camera state (fov, position, etc..)
  20134. */
  20135. Camera.prototype.storeState = function () {
  20136. this._stateStored = true;
  20137. this._storedFov = this.fov;
  20138. return this;
  20139. };
  20140. /**
  20141. * Restores the camera state values if it has been stored. You must call storeState() first
  20142. */
  20143. Camera.prototype._restoreStateValues = function () {
  20144. if (!this._stateStored) {
  20145. return false;
  20146. }
  20147. this.fov = this._storedFov;
  20148. return true;
  20149. };
  20150. /**
  20151. * Restored camera state. You must call storeState() first
  20152. */
  20153. Camera.prototype.restoreState = function () {
  20154. if (this._restoreStateValues()) {
  20155. this.onRestoreStateObservable.notifyObservers(this);
  20156. return true;
  20157. }
  20158. return false;
  20159. };
  20160. Camera.prototype.getClassName = function () {
  20161. return "Camera";
  20162. };
  20163. /**
  20164. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20165. */
  20166. Camera.prototype.toString = function (fullDetails) {
  20167. var ret = "Name: " + this.name;
  20168. ret += ", type: " + this.getClassName();
  20169. if (this.animations) {
  20170. for (var i = 0; i < this.animations.length; i++) {
  20171. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20172. }
  20173. }
  20174. if (fullDetails) {
  20175. }
  20176. return ret;
  20177. };
  20178. Object.defineProperty(Camera.prototype, "globalPosition", {
  20179. get: function () {
  20180. return this._globalPosition;
  20181. },
  20182. enumerable: true,
  20183. configurable: true
  20184. });
  20185. Camera.prototype.getActiveMeshes = function () {
  20186. return this._activeMeshes;
  20187. };
  20188. Camera.prototype.isActiveMesh = function (mesh) {
  20189. return (this._activeMeshes.indexOf(mesh) !== -1);
  20190. };
  20191. /**
  20192. * Is this camera ready to be used/rendered
  20193. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20194. * @return true if the camera is ready
  20195. */
  20196. Camera.prototype.isReady = function (completeCheck) {
  20197. if (completeCheck === void 0) { completeCheck = false; }
  20198. if (completeCheck) {
  20199. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20200. var pp = _a[_i];
  20201. if (pp && !pp.isReady()) {
  20202. return false;
  20203. }
  20204. }
  20205. }
  20206. return _super.prototype.isReady.call(this, completeCheck);
  20207. };
  20208. //Cache
  20209. Camera.prototype._initCache = function () {
  20210. _super.prototype._initCache.call(this);
  20211. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20212. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20213. this._cache.mode = undefined;
  20214. this._cache.minZ = undefined;
  20215. this._cache.maxZ = undefined;
  20216. this._cache.fov = undefined;
  20217. this._cache.fovMode = undefined;
  20218. this._cache.aspectRatio = undefined;
  20219. this._cache.orthoLeft = undefined;
  20220. this._cache.orthoRight = undefined;
  20221. this._cache.orthoBottom = undefined;
  20222. this._cache.orthoTop = undefined;
  20223. this._cache.renderWidth = undefined;
  20224. this._cache.renderHeight = undefined;
  20225. };
  20226. Camera.prototype._updateCache = function (ignoreParentClass) {
  20227. if (!ignoreParentClass) {
  20228. _super.prototype._updateCache.call(this);
  20229. }
  20230. this._cache.position.copyFrom(this.position);
  20231. this._cache.upVector.copyFrom(this.upVector);
  20232. };
  20233. // Synchronized
  20234. Camera.prototype._isSynchronized = function () {
  20235. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20236. };
  20237. Camera.prototype._isSynchronizedViewMatrix = function () {
  20238. if (!_super.prototype._isSynchronized.call(this))
  20239. return false;
  20240. return this._cache.position.equals(this.position)
  20241. && this._cache.upVector.equals(this.upVector)
  20242. && this.isSynchronizedWithParent();
  20243. };
  20244. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20245. var check = this._cache.mode === this.mode
  20246. && this._cache.minZ === this.minZ
  20247. && this._cache.maxZ === this.maxZ;
  20248. if (!check) {
  20249. return false;
  20250. }
  20251. var engine = this.getEngine();
  20252. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20253. check = this._cache.fov === this.fov
  20254. && this._cache.fovMode === this.fovMode
  20255. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20256. }
  20257. else {
  20258. check = this._cache.orthoLeft === this.orthoLeft
  20259. && this._cache.orthoRight === this.orthoRight
  20260. && this._cache.orthoBottom === this.orthoBottom
  20261. && this._cache.orthoTop === this.orthoTop
  20262. && this._cache.renderWidth === engine.getRenderWidth()
  20263. && this._cache.renderHeight === engine.getRenderHeight();
  20264. }
  20265. return check;
  20266. };
  20267. // Controls
  20268. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20269. };
  20270. Camera.prototype.detachControl = function (element) {
  20271. };
  20272. Camera.prototype.update = function () {
  20273. this._checkInputs();
  20274. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20275. this._updateRigCameras();
  20276. }
  20277. };
  20278. Camera.prototype._checkInputs = function () {
  20279. this.onAfterCheckInputsObservable.notifyObservers(this);
  20280. };
  20281. Object.defineProperty(Camera.prototype, "rigCameras", {
  20282. get: function () {
  20283. return this._rigCameras;
  20284. },
  20285. enumerable: true,
  20286. configurable: true
  20287. });
  20288. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20289. get: function () {
  20290. return this._rigPostProcess;
  20291. },
  20292. enumerable: true,
  20293. configurable: true
  20294. });
  20295. /**
  20296. * Internal, gets the first post proces.
  20297. * @returns the first post process to be run on this camera.
  20298. */
  20299. Camera.prototype._getFirstPostProcess = function () {
  20300. for (var pp in this._postProcesses) {
  20301. if (this._postProcesses[pp] !== null) {
  20302. return this._postProcesses[pp];
  20303. }
  20304. }
  20305. return null;
  20306. };
  20307. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20308. // invalidate framebuffer
  20309. var firstPostProcess = this._getFirstPostProcess();
  20310. if (firstPostProcess) {
  20311. firstPostProcess.markTextureDirty();
  20312. }
  20313. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20314. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20315. var cam = this._rigCameras[i];
  20316. var rigPostProcess = cam._rigPostProcess;
  20317. // for VR rig, there does not have to be a post process
  20318. if (rigPostProcess) {
  20319. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20320. if (isPass) {
  20321. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20322. cam.isIntermediate = this._postProcesses.length === 0;
  20323. }
  20324. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20325. rigPostProcess.markTextureDirty();
  20326. }
  20327. else {
  20328. cam._postProcesses = this._postProcesses.slice(0);
  20329. }
  20330. }
  20331. };
  20332. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20333. if (insertAt === void 0) { insertAt = null; }
  20334. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20335. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20336. return 0;
  20337. }
  20338. if (insertAt == null || insertAt < 0) {
  20339. this._postProcesses.push(postProcess);
  20340. }
  20341. else if (this._postProcesses[insertAt] === null) {
  20342. this._postProcesses[insertAt] = postProcess;
  20343. }
  20344. else {
  20345. this._postProcesses.splice(insertAt, 0, postProcess);
  20346. }
  20347. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20348. return this._postProcesses.indexOf(postProcess);
  20349. };
  20350. Camera.prototype.detachPostProcess = function (postProcess) {
  20351. var idx = this._postProcesses.indexOf(postProcess);
  20352. if (idx !== -1) {
  20353. this._postProcesses[idx] = null;
  20354. }
  20355. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20356. };
  20357. Camera.prototype.getWorldMatrix = function () {
  20358. if (!this._worldMatrix) {
  20359. this._worldMatrix = BABYLON.Matrix.Identity();
  20360. }
  20361. var viewMatrix = this.getViewMatrix();
  20362. viewMatrix.invertToRef(this._worldMatrix);
  20363. return this._worldMatrix;
  20364. };
  20365. Camera.prototype._getViewMatrix = function () {
  20366. return BABYLON.Matrix.Identity();
  20367. };
  20368. Camera.prototype.getViewMatrix = function (force) {
  20369. if (!force && this._isSynchronizedViewMatrix()) {
  20370. return this._computedViewMatrix;
  20371. }
  20372. this.updateCache();
  20373. this._computedViewMatrix = this._getViewMatrix();
  20374. this._currentRenderId = this.getScene().getRenderId();
  20375. this._childRenderId = this._currentRenderId;
  20376. this._refreshFrustumPlanes = true;
  20377. if (!this.parent || !this.parent.getWorldMatrix) {
  20378. this._globalPosition.copyFrom(this.position);
  20379. }
  20380. else {
  20381. if (!this._worldMatrix) {
  20382. this._worldMatrix = BABYLON.Matrix.Identity();
  20383. }
  20384. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20385. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20386. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20387. this._computedViewMatrix.invert();
  20388. this._markSyncedWithParent();
  20389. }
  20390. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20391. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20392. }
  20393. this.onViewMatrixChangedObservable.notifyObservers(this);
  20394. return this._computedViewMatrix;
  20395. };
  20396. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20397. this._doNotComputeProjectionMatrix = true;
  20398. if (projection !== undefined) {
  20399. this._projectionMatrix = projection;
  20400. }
  20401. };
  20402. ;
  20403. Camera.prototype.unfreezeProjectionMatrix = function () {
  20404. this._doNotComputeProjectionMatrix = false;
  20405. };
  20406. ;
  20407. Camera.prototype.getProjectionMatrix = function (force) {
  20408. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20409. return this._projectionMatrix;
  20410. }
  20411. // Cache
  20412. this._cache.mode = this.mode;
  20413. this._cache.minZ = this.minZ;
  20414. this._cache.maxZ = this.maxZ;
  20415. // Matrix
  20416. this._refreshFrustumPlanes = true;
  20417. var engine = this.getEngine();
  20418. var scene = this.getScene();
  20419. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20420. this._cache.fov = this.fov;
  20421. this._cache.fovMode = this.fovMode;
  20422. this._cache.aspectRatio = engine.getAspectRatio(this);
  20423. if (this.minZ <= 0) {
  20424. this.minZ = 0.1;
  20425. }
  20426. if (scene.useRightHandedSystem) {
  20427. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20428. }
  20429. else {
  20430. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20431. }
  20432. }
  20433. else {
  20434. var halfWidth = engine.getRenderWidth() / 2.0;
  20435. var halfHeight = engine.getRenderHeight() / 2.0;
  20436. if (scene.useRightHandedSystem) {
  20437. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20438. }
  20439. else {
  20440. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20441. }
  20442. this._cache.orthoLeft = this.orthoLeft;
  20443. this._cache.orthoRight = this.orthoRight;
  20444. this._cache.orthoBottom = this.orthoBottom;
  20445. this._cache.orthoTop = this.orthoTop;
  20446. this._cache.renderWidth = engine.getRenderWidth();
  20447. this._cache.renderHeight = engine.getRenderHeight();
  20448. }
  20449. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20450. return this._projectionMatrix;
  20451. };
  20452. Camera.prototype.getTranformationMatrix = function () {
  20453. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20454. return this._transformMatrix;
  20455. };
  20456. Camera.prototype.updateFrustumPlanes = function () {
  20457. if (!this._refreshFrustumPlanes) {
  20458. return;
  20459. }
  20460. this.getTranformationMatrix();
  20461. if (!this._frustumPlanes) {
  20462. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20463. }
  20464. else {
  20465. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20466. }
  20467. this._refreshFrustumPlanes = false;
  20468. };
  20469. Camera.prototype.isInFrustum = function (target) {
  20470. this.updateFrustumPlanes();
  20471. return target.isInFrustum(this._frustumPlanes);
  20472. };
  20473. Camera.prototype.isCompletelyInFrustum = function (target) {
  20474. this.updateFrustumPlanes();
  20475. return target.isCompletelyInFrustum(this._frustumPlanes);
  20476. };
  20477. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20478. if (length === void 0) { length = 100; }
  20479. if (!transform) {
  20480. transform = this.getWorldMatrix();
  20481. }
  20482. if (!origin) {
  20483. origin = this.position;
  20484. }
  20485. var forward = new BABYLON.Vector3(0, 0, 1);
  20486. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20487. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20488. return new BABYLON.Ray(origin, direction, length);
  20489. };
  20490. /**
  20491. * Releases resources associated with this node.
  20492. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20493. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20494. */
  20495. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20496. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20497. // Observables
  20498. this.onViewMatrixChangedObservable.clear();
  20499. this.onProjectionMatrixChangedObservable.clear();
  20500. this.onAfterCheckInputsObservable.clear();
  20501. this.onRestoreStateObservable.clear();
  20502. // Inputs
  20503. if (this.inputs) {
  20504. this.inputs.clear();
  20505. }
  20506. // Animations
  20507. this.getScene().stopAnimation(this);
  20508. // Remove from scene
  20509. this.getScene().removeCamera(this);
  20510. while (this._rigCameras.length > 0) {
  20511. var camera = this._rigCameras.pop();
  20512. if (camera) {
  20513. camera.dispose();
  20514. }
  20515. }
  20516. // Postprocesses
  20517. if (this._rigPostProcess) {
  20518. this._rigPostProcess.dispose(this);
  20519. this._rigPostProcess = null;
  20520. this._postProcesses = [];
  20521. }
  20522. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20523. this._rigPostProcess = null;
  20524. this._postProcesses = [];
  20525. }
  20526. else {
  20527. var i = this._postProcesses.length;
  20528. while (--i >= 0) {
  20529. var postProcess = this._postProcesses[i];
  20530. if (postProcess) {
  20531. postProcess.dispose(this);
  20532. }
  20533. }
  20534. }
  20535. // Render targets
  20536. var i = this.customRenderTargets.length;
  20537. while (--i >= 0) {
  20538. this.customRenderTargets[i].dispose();
  20539. }
  20540. this.customRenderTargets = [];
  20541. // Active Meshes
  20542. this._activeMeshes.dispose();
  20543. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20544. };
  20545. Object.defineProperty(Camera.prototype, "leftCamera", {
  20546. // ---- Camera rigs section ----
  20547. get: function () {
  20548. if (this._rigCameras.length < 1) {
  20549. return null;
  20550. }
  20551. return this._rigCameras[0];
  20552. },
  20553. enumerable: true,
  20554. configurable: true
  20555. });
  20556. Object.defineProperty(Camera.prototype, "rightCamera", {
  20557. get: function () {
  20558. if (this._rigCameras.length < 2) {
  20559. return null;
  20560. }
  20561. return this._rigCameras[1];
  20562. },
  20563. enumerable: true,
  20564. configurable: true
  20565. });
  20566. Camera.prototype.getLeftTarget = function () {
  20567. if (this._rigCameras.length < 1) {
  20568. return null;
  20569. }
  20570. return this._rigCameras[0].getTarget();
  20571. };
  20572. Camera.prototype.getRightTarget = function () {
  20573. if (this._rigCameras.length < 2) {
  20574. return null;
  20575. }
  20576. return this._rigCameras[1].getTarget();
  20577. };
  20578. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20579. if (this.cameraRigMode === mode) {
  20580. return;
  20581. }
  20582. while (this._rigCameras.length > 0) {
  20583. var camera = this._rigCameras.pop();
  20584. if (camera) {
  20585. camera.dispose();
  20586. }
  20587. }
  20588. this.cameraRigMode = mode;
  20589. this._cameraRigParams = {};
  20590. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20591. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20592. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20593. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20594. // create the rig cameras, unless none
  20595. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20596. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20597. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20598. if (leftCamera && rightCamera) {
  20599. this._rigCameras.push(leftCamera);
  20600. this._rigCameras.push(rightCamera);
  20601. }
  20602. }
  20603. switch (this.cameraRigMode) {
  20604. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20605. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20606. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20607. break;
  20608. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20609. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20610. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20611. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20612. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20613. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20614. break;
  20615. case Camera.RIG_MODE_VR:
  20616. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20617. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20618. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20619. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20620. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20621. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20622. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20623. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20624. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20625. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20626. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20627. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20628. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20629. if (metrics.compensateDistortion) {
  20630. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20631. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20632. }
  20633. break;
  20634. case Camera.RIG_MODE_WEBVR:
  20635. if (rigParams.vrDisplay) {
  20636. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20637. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20638. //Left eye
  20639. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20640. this._rigCameras[0].setCameraRigParameter("left", true);
  20641. //leaving this for future reference
  20642. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20643. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20644. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20645. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20646. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20647. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20648. this._rigCameras[0].parent = this;
  20649. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20650. //Right eye
  20651. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20652. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20653. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20654. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20655. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20656. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20657. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20658. this._rigCameras[1].parent = this;
  20659. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20660. if (Camera.UseAlternateWebVRRendering) {
  20661. this._rigCameras[1]._skipRendering = true;
  20662. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20663. }
  20664. }
  20665. break;
  20666. }
  20667. this._cascadePostProcessesToRigCams();
  20668. this.update();
  20669. };
  20670. Camera.prototype._getVRProjectionMatrix = function () {
  20671. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20672. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20673. return this._projectionMatrix;
  20674. };
  20675. Camera.prototype._updateCameraRotationMatrix = function () {
  20676. //Here for WebVR
  20677. };
  20678. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20679. //Here for WebVR
  20680. };
  20681. /**
  20682. * This function MUST be overwritten by the different WebVR cameras available.
  20683. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20684. */
  20685. Camera.prototype._getWebVRProjectionMatrix = function () {
  20686. return BABYLON.Matrix.Identity();
  20687. };
  20688. /**
  20689. * This function MUST be overwritten by the different WebVR cameras available.
  20690. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20691. */
  20692. Camera.prototype._getWebVRViewMatrix = function () {
  20693. return BABYLON.Matrix.Identity();
  20694. };
  20695. Camera.prototype.setCameraRigParameter = function (name, value) {
  20696. if (!this._cameraRigParams) {
  20697. this._cameraRigParams = {};
  20698. }
  20699. this._cameraRigParams[name] = value;
  20700. //provisionnally:
  20701. if (name === "interaxialDistance") {
  20702. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20703. }
  20704. };
  20705. /**
  20706. * needs to be overridden by children so sub has required properties to be copied
  20707. */
  20708. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20709. return null;
  20710. };
  20711. /**
  20712. * May need to be overridden by children
  20713. */
  20714. Camera.prototype._updateRigCameras = function () {
  20715. for (var i = 0; i < this._rigCameras.length; i++) {
  20716. this._rigCameras[i].minZ = this.minZ;
  20717. this._rigCameras[i].maxZ = this.maxZ;
  20718. this._rigCameras[i].fov = this.fov;
  20719. }
  20720. // only update viewport when ANAGLYPH
  20721. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20722. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20723. }
  20724. };
  20725. Camera.prototype._setupInputs = function () {
  20726. };
  20727. Camera.prototype.serialize = function () {
  20728. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20729. // Type
  20730. serializationObject.type = this.getClassName();
  20731. // Parent
  20732. if (this.parent) {
  20733. serializationObject.parentId = this.parent.id;
  20734. }
  20735. if (this.inputs) {
  20736. this.inputs.serialize(serializationObject);
  20737. }
  20738. // Animations
  20739. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20740. serializationObject.ranges = this.serializeAnimationRanges();
  20741. return serializationObject;
  20742. };
  20743. Camera.prototype.clone = function (name) {
  20744. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20745. };
  20746. Camera.prototype.getDirection = function (localAxis) {
  20747. var result = BABYLON.Vector3.Zero();
  20748. this.getDirectionToRef(localAxis, result);
  20749. return result;
  20750. };
  20751. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20752. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20753. };
  20754. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20755. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20756. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20757. switch (type) {
  20758. case "ArcRotateCamera":
  20759. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20760. case "DeviceOrientationCamera":
  20761. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20762. case "FollowCamera":
  20763. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20764. case "ArcFollowCamera":
  20765. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20766. case "GamepadCamera":
  20767. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20768. case "TouchCamera":
  20769. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20770. case "VirtualJoysticksCamera":
  20771. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20772. case "WebVRFreeCamera":
  20773. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20774. case "WebVRGamepadCamera":
  20775. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20776. case "VRDeviceOrientationFreeCamera":
  20777. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20778. case "VRDeviceOrientationGamepadCamera":
  20779. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20780. case "AnaglyphArcRotateCamera":
  20781. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20782. case "AnaglyphFreeCamera":
  20783. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20784. case "AnaglyphGamepadCamera":
  20785. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20786. case "AnaglyphUniversalCamera":
  20787. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20788. case "StereoscopicArcRotateCamera":
  20789. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20790. case "StereoscopicFreeCamera":
  20791. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20792. case "StereoscopicGamepadCamera":
  20793. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20794. case "StereoscopicUniversalCamera":
  20795. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20796. case "FreeCamera":// Forcing Universal here
  20797. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20798. default:// Universal Camera is the default value
  20799. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20800. }
  20801. };
  20802. Camera.prototype.computeWorldMatrix = function () {
  20803. return this.getWorldMatrix();
  20804. };
  20805. Camera.Parse = function (parsedCamera, scene) {
  20806. var type = parsedCamera.type;
  20807. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20808. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20809. // Parent
  20810. if (parsedCamera.parentId) {
  20811. camera._waitingParentId = parsedCamera.parentId;
  20812. }
  20813. //If camera has an input manager, let it parse inputs settings
  20814. if (camera.inputs) {
  20815. camera.inputs.parse(parsedCamera);
  20816. camera._setupInputs();
  20817. }
  20818. if (camera.setPosition) {
  20819. camera.position.copyFromFloats(0, 0, 0);
  20820. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20821. }
  20822. // Target
  20823. if (parsedCamera.target) {
  20824. if (camera.setTarget) {
  20825. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20826. }
  20827. }
  20828. // Apply 3d rig, when found
  20829. if (parsedCamera.cameraRigMode) {
  20830. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20831. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20832. }
  20833. // Animations
  20834. if (parsedCamera.animations) {
  20835. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20836. var parsedAnimation = parsedCamera.animations[animationIndex];
  20837. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20838. }
  20839. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20840. }
  20841. if (parsedCamera.autoAnimate) {
  20842. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20843. }
  20844. return camera;
  20845. };
  20846. // Statics
  20847. Camera._PERSPECTIVE_CAMERA = 0;
  20848. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20849. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20850. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20851. Camera._RIG_MODE_NONE = 0;
  20852. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20853. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20854. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20855. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20856. Camera._RIG_MODE_VR = 20;
  20857. Camera._RIG_MODE_WEBVR = 21;
  20858. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20859. Camera.UseAlternateWebVRRendering = false;
  20860. __decorate([
  20861. BABYLON.serializeAsVector3()
  20862. ], Camera.prototype, "position", void 0);
  20863. __decorate([
  20864. BABYLON.serializeAsVector3()
  20865. ], Camera.prototype, "upVector", void 0);
  20866. __decorate([
  20867. BABYLON.serialize()
  20868. ], Camera.prototype, "orthoLeft", void 0);
  20869. __decorate([
  20870. BABYLON.serialize()
  20871. ], Camera.prototype, "orthoRight", void 0);
  20872. __decorate([
  20873. BABYLON.serialize()
  20874. ], Camera.prototype, "orthoBottom", void 0);
  20875. __decorate([
  20876. BABYLON.serialize()
  20877. ], Camera.prototype, "orthoTop", void 0);
  20878. __decorate([
  20879. BABYLON.serialize()
  20880. ], Camera.prototype, "fov", void 0);
  20881. __decorate([
  20882. BABYLON.serialize()
  20883. ], Camera.prototype, "minZ", void 0);
  20884. __decorate([
  20885. BABYLON.serialize()
  20886. ], Camera.prototype, "maxZ", void 0);
  20887. __decorate([
  20888. BABYLON.serialize()
  20889. ], Camera.prototype, "inertia", void 0);
  20890. __decorate([
  20891. BABYLON.serialize()
  20892. ], Camera.prototype, "mode", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], Camera.prototype, "layerMask", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], Camera.prototype, "fovMode", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], Camera.prototype, "cameraRigMode", void 0);
  20902. __decorate([
  20903. BABYLON.serialize()
  20904. ], Camera.prototype, "interaxialDistance", void 0);
  20905. __decorate([
  20906. BABYLON.serialize()
  20907. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20908. return Camera;
  20909. }(BABYLON.Node));
  20910. BABYLON.Camera = Camera;
  20911. })(BABYLON || (BABYLON = {}));
  20912. //# sourceMappingURL=babylon.camera.js.map
  20913. "use strict";
  20914. var BABYLON;
  20915. (function (BABYLON) {
  20916. var RenderingManager = /** @class */ (function () {
  20917. function RenderingManager(scene) {
  20918. this._renderingGroups = new Array();
  20919. this._autoClearDepthStencil = {};
  20920. this._customOpaqueSortCompareFn = {};
  20921. this._customAlphaTestSortCompareFn = {};
  20922. this._customTransparentSortCompareFn = {};
  20923. this._renderinGroupInfo = null;
  20924. this._scene = scene;
  20925. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20926. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20927. }
  20928. }
  20929. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20930. if (depth === void 0) { depth = true; }
  20931. if (stencil === void 0) { stencil = true; }
  20932. if (this._depthStencilBufferAlreadyCleaned) {
  20933. return;
  20934. }
  20935. this._scene.getEngine().clear(null, false, depth, stencil);
  20936. this._depthStencilBufferAlreadyCleaned = true;
  20937. };
  20938. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20939. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20940. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20941. var info = null;
  20942. if (observable) {
  20943. if (!this._renderinGroupInfo) {
  20944. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20945. }
  20946. info = this._renderinGroupInfo;
  20947. info.scene = this._scene;
  20948. info.camera = this._scene.activeCamera;
  20949. }
  20950. // Dispatch sprites
  20951. if (renderSprites) {
  20952. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20953. var manager = this._scene.spriteManagers[index];
  20954. this.dispatchSprites(manager);
  20955. }
  20956. }
  20957. // Render
  20958. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20959. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20960. var renderingGroup = this._renderingGroups[index];
  20961. if (!renderingGroup && !observable)
  20962. continue;
  20963. var renderingGroupMask = 0;
  20964. // Fire PRECLEAR stage
  20965. if (observable && info) {
  20966. renderingGroupMask = Math.pow(2, index);
  20967. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20968. info.renderingGroupId = index;
  20969. observable.notifyObservers(info, renderingGroupMask);
  20970. }
  20971. // Clear depth/stencil if needed
  20972. if (RenderingManager.AUTOCLEAR) {
  20973. var autoClear = this._autoClearDepthStencil[index];
  20974. if (autoClear && autoClear.autoClear) {
  20975. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20976. }
  20977. }
  20978. if (observable && info) {
  20979. // Fire PREOPAQUE stage
  20980. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20981. observable.notifyObservers(info, renderingGroupMask);
  20982. // Fire PRETRANSPARENT stage
  20983. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20984. observable.notifyObservers(info, renderingGroupMask);
  20985. }
  20986. if (renderingGroup)
  20987. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20988. // Fire POSTTRANSPARENT stage
  20989. if (observable && info) {
  20990. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20991. observable.notifyObservers(info, renderingGroupMask);
  20992. }
  20993. }
  20994. };
  20995. RenderingManager.prototype.reset = function () {
  20996. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20997. var renderingGroup = this._renderingGroups[index];
  20998. if (renderingGroup) {
  20999. renderingGroup.prepare();
  21000. }
  21001. }
  21002. };
  21003. RenderingManager.prototype.dispose = function () {
  21004. this.freeRenderingGroups();
  21005. this._renderingGroups.length = 0;
  21006. };
  21007. /**
  21008. * Clear the info related to rendering groups preventing retention points during dispose.
  21009. */
  21010. RenderingManager.prototype.freeRenderingGroups = function () {
  21011. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21012. var renderingGroup = this._renderingGroups[index];
  21013. if (renderingGroup) {
  21014. renderingGroup.dispose();
  21015. }
  21016. }
  21017. };
  21018. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21019. if (this._renderingGroups[renderingGroupId] === undefined) {
  21020. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21021. }
  21022. };
  21023. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21024. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21025. this._prepareRenderingGroup(renderingGroupId);
  21026. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21027. };
  21028. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21029. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21030. this._prepareRenderingGroup(renderingGroupId);
  21031. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21032. };
  21033. /**
  21034. * @param subMesh The submesh to dispatch
  21035. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21036. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21037. */
  21038. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21039. if (mesh === undefined) {
  21040. mesh = subMesh.getMesh();
  21041. }
  21042. var renderingGroupId = mesh.renderingGroupId || 0;
  21043. this._prepareRenderingGroup(renderingGroupId);
  21044. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21045. };
  21046. /**
  21047. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21048. * This allowed control for front to back rendering or reversly depending of the special needs.
  21049. *
  21050. * @param renderingGroupId The rendering group id corresponding to its index
  21051. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21052. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21053. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21054. */
  21055. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21056. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21057. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21058. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21059. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21060. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21061. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21062. if (this._renderingGroups[renderingGroupId]) {
  21063. var group = this._renderingGroups[renderingGroupId];
  21064. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21065. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21066. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21067. }
  21068. };
  21069. /**
  21070. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21071. *
  21072. * @param renderingGroupId The rendering group id corresponding to its index
  21073. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21074. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21075. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21076. */
  21077. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21078. if (depth === void 0) { depth = true; }
  21079. if (stencil === void 0) { stencil = true; }
  21080. this._autoClearDepthStencil[renderingGroupId] = {
  21081. autoClear: autoClearDepthStencil,
  21082. depth: depth,
  21083. stencil: stencil
  21084. };
  21085. };
  21086. /**
  21087. * The max id used for rendering groups (not included)
  21088. */
  21089. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21090. /**
  21091. * The min id used for rendering groups (included)
  21092. */
  21093. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21094. /**
  21095. * Used to globally prevent autoclearing scenes.
  21096. */
  21097. RenderingManager.AUTOCLEAR = true;
  21098. return RenderingManager;
  21099. }());
  21100. BABYLON.RenderingManager = RenderingManager;
  21101. })(BABYLON || (BABYLON = {}));
  21102. //# sourceMappingURL=babylon.renderingManager.js.map
  21103. "use strict";
  21104. var BABYLON;
  21105. (function (BABYLON) {
  21106. var RenderingGroup = /** @class */ (function () {
  21107. /**
  21108. * Creates a new rendering group.
  21109. * @param index The rendering group index
  21110. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21111. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21112. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21113. */
  21114. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21115. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21116. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21117. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21118. this.index = index;
  21119. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21120. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21121. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21122. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21123. this._particleSystems = new BABYLON.SmartArray(256);
  21124. this._spriteManagers = new BABYLON.SmartArray(256);
  21125. this._edgesRenderers = new BABYLON.SmartArray(16);
  21126. this._scene = scene;
  21127. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21128. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21129. this.transparentSortCompareFn = transparentSortCompareFn;
  21130. }
  21131. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21132. /**
  21133. * Set the opaque sort comparison function.
  21134. * If null the sub meshes will be render in the order they were created
  21135. */
  21136. set: function (value) {
  21137. this._opaqueSortCompareFn = value;
  21138. if (value) {
  21139. this._renderOpaque = this.renderOpaqueSorted;
  21140. }
  21141. else {
  21142. this._renderOpaque = RenderingGroup.renderUnsorted;
  21143. }
  21144. },
  21145. enumerable: true,
  21146. configurable: true
  21147. });
  21148. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21149. /**
  21150. * Set the alpha test sort comparison function.
  21151. * If null the sub meshes will be render in the order they were created
  21152. */
  21153. set: function (value) {
  21154. this._alphaTestSortCompareFn = value;
  21155. if (value) {
  21156. this._renderAlphaTest = this.renderAlphaTestSorted;
  21157. }
  21158. else {
  21159. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21160. }
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21166. /**
  21167. * Set the transparent sort comparison function.
  21168. * If null the sub meshes will be render in the order they were created
  21169. */
  21170. set: function (value) {
  21171. if (value) {
  21172. this._transparentSortCompareFn = value;
  21173. }
  21174. else {
  21175. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21176. }
  21177. this._renderTransparent = this.renderTransparentSorted;
  21178. },
  21179. enumerable: true,
  21180. configurable: true
  21181. });
  21182. /**
  21183. * Render all the sub meshes contained in the group.
  21184. * @param customRenderFunction Used to override the default render behaviour of the group.
  21185. * @returns true if rendered some submeshes.
  21186. */
  21187. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21188. if (customRenderFunction) {
  21189. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21190. return;
  21191. }
  21192. var engine = this._scene.getEngine();
  21193. // Depth only
  21194. if (this._depthOnlySubMeshes.length !== 0) {
  21195. engine.setColorWrite(false);
  21196. this._renderAlphaTest(this._depthOnlySubMeshes);
  21197. engine.setColorWrite(true);
  21198. }
  21199. // Opaque
  21200. if (this._opaqueSubMeshes.length !== 0) {
  21201. this._renderOpaque(this._opaqueSubMeshes);
  21202. }
  21203. // Alpha test
  21204. if (this._alphaTestSubMeshes.length !== 0) {
  21205. this._renderAlphaTest(this._alphaTestSubMeshes);
  21206. }
  21207. var stencilState = engine.getStencilBuffer();
  21208. engine.setStencilBuffer(false);
  21209. // Sprites
  21210. if (renderSprites) {
  21211. this._renderSprites();
  21212. }
  21213. // Particles
  21214. if (renderParticles) {
  21215. this._renderParticles(activeMeshes);
  21216. }
  21217. if (this.onBeforeTransparentRendering) {
  21218. this.onBeforeTransparentRendering();
  21219. }
  21220. // Transparent
  21221. if (this._transparentSubMeshes.length !== 0) {
  21222. this._renderTransparent(this._transparentSubMeshes);
  21223. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21224. }
  21225. // Set back stencil to false in case it changes before the edge renderer.
  21226. engine.setStencilBuffer(false);
  21227. // Edges
  21228. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21229. this._edgesRenderers.data[edgesRendererIndex].render();
  21230. }
  21231. // Restore Stencil state.
  21232. engine.setStencilBuffer(stencilState);
  21233. };
  21234. /**
  21235. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21236. * @param subMeshes The submeshes to render
  21237. */
  21238. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21239. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21240. };
  21241. /**
  21242. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21243. * @param subMeshes The submeshes to render
  21244. */
  21245. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21246. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21247. };
  21248. /**
  21249. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21250. * @param subMeshes The submeshes to render
  21251. */
  21252. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21253. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21254. };
  21255. /**
  21256. * Renders the submeshes in a specified order.
  21257. * @param subMeshes The submeshes to sort before render
  21258. * @param sortCompareFn The comparison function use to sort
  21259. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21260. * @param transparent Specifies to activate blending if true
  21261. */
  21262. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21263. var subIndex = 0;
  21264. var subMesh;
  21265. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21266. for (; subIndex < subMeshes.length; subIndex++) {
  21267. subMesh = subMeshes.data[subIndex];
  21268. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21269. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21270. }
  21271. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21272. if (sortCompareFn) {
  21273. sortedArray.sort(sortCompareFn);
  21274. }
  21275. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21276. subMesh = sortedArray[subIndex];
  21277. if (transparent) {
  21278. var material = subMesh.getMaterial();
  21279. if (material && material.needDepthPrePass) {
  21280. var engine = material.getScene().getEngine();
  21281. engine.setColorWrite(false);
  21282. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21283. subMesh.render(false);
  21284. engine.setColorWrite(true);
  21285. }
  21286. }
  21287. subMesh.render(transparent);
  21288. }
  21289. };
  21290. /**
  21291. * Renders the submeshes in the order they were dispatched (no sort applied).
  21292. * @param subMeshes The submeshes to render
  21293. */
  21294. RenderingGroup.renderUnsorted = function (subMeshes) {
  21295. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21296. var submesh = subMeshes.data[subIndex];
  21297. submesh.render(false);
  21298. }
  21299. };
  21300. /**
  21301. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21302. * are rendered back to front if in the same alpha index.
  21303. *
  21304. * @param a The first submesh
  21305. * @param b The second submesh
  21306. * @returns The result of the comparison
  21307. */
  21308. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21309. // Alpha index first
  21310. if (a._alphaIndex > b._alphaIndex) {
  21311. return 1;
  21312. }
  21313. if (a._alphaIndex < b._alphaIndex) {
  21314. return -1;
  21315. }
  21316. // Then distance to camera
  21317. return RenderingGroup.backToFrontSortCompare(a, b);
  21318. };
  21319. /**
  21320. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21321. * are rendered back to front.
  21322. *
  21323. * @param a The first submesh
  21324. * @param b The second submesh
  21325. * @returns The result of the comparison
  21326. */
  21327. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21328. // Then distance to camera
  21329. if (a._distanceToCamera < b._distanceToCamera) {
  21330. return 1;
  21331. }
  21332. if (a._distanceToCamera > b._distanceToCamera) {
  21333. return -1;
  21334. }
  21335. return 0;
  21336. };
  21337. /**
  21338. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21339. * are rendered front to back (prevent overdraw).
  21340. *
  21341. * @param a The first submesh
  21342. * @param b The second submesh
  21343. * @returns The result of the comparison
  21344. */
  21345. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21346. // Then distance to camera
  21347. if (a._distanceToCamera < b._distanceToCamera) {
  21348. return -1;
  21349. }
  21350. if (a._distanceToCamera > b._distanceToCamera) {
  21351. return 1;
  21352. }
  21353. return 0;
  21354. };
  21355. /**
  21356. * Resets the different lists of submeshes to prepare a new frame.
  21357. */
  21358. RenderingGroup.prototype.prepare = function () {
  21359. this._opaqueSubMeshes.reset();
  21360. this._transparentSubMeshes.reset();
  21361. this._alphaTestSubMeshes.reset();
  21362. this._depthOnlySubMeshes.reset();
  21363. this._particleSystems.reset();
  21364. this._spriteManagers.reset();
  21365. this._edgesRenderers.reset();
  21366. };
  21367. RenderingGroup.prototype.dispose = function () {
  21368. this._opaqueSubMeshes.dispose();
  21369. this._transparentSubMeshes.dispose();
  21370. this._alphaTestSubMeshes.dispose();
  21371. this._depthOnlySubMeshes.dispose();
  21372. this._particleSystems.dispose();
  21373. this._spriteManagers.dispose();
  21374. this._edgesRenderers.dispose();
  21375. };
  21376. /**
  21377. * Inserts the submesh in its correct queue depending on its material.
  21378. * @param subMesh The submesh to dispatch
  21379. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21380. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21381. */
  21382. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21383. // Get mesh and materials if not provided
  21384. if (mesh === undefined) {
  21385. mesh = subMesh.getMesh();
  21386. }
  21387. if (material === undefined) {
  21388. material = subMesh.getMaterial();
  21389. }
  21390. if (material === null || material === undefined) {
  21391. return;
  21392. }
  21393. if (material.needAlphaBlendingForMesh(mesh)) {
  21394. this._transparentSubMeshes.push(subMesh);
  21395. }
  21396. else if (material.needAlphaTesting()) {
  21397. if (material.needDepthPrePass) {
  21398. this._depthOnlySubMeshes.push(subMesh);
  21399. }
  21400. this._alphaTestSubMeshes.push(subMesh);
  21401. }
  21402. else {
  21403. if (material.needDepthPrePass) {
  21404. this._depthOnlySubMeshes.push(subMesh);
  21405. }
  21406. this._opaqueSubMeshes.push(subMesh); // Opaque
  21407. }
  21408. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21409. this._edgesRenderers.push(mesh._edgesRenderer);
  21410. }
  21411. };
  21412. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21413. this._spriteManagers.push(spriteManager);
  21414. };
  21415. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21416. this._particleSystems.push(particleSystem);
  21417. };
  21418. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21419. if (this._particleSystems.length === 0) {
  21420. return;
  21421. }
  21422. // Particles
  21423. var activeCamera = this._scene.activeCamera;
  21424. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21425. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21426. var particleSystem = this._particleSystems.data[particleIndex];
  21427. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21428. continue;
  21429. }
  21430. var emitter = particleSystem.emitter;
  21431. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21432. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21433. }
  21434. }
  21435. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21436. };
  21437. RenderingGroup.prototype._renderSprites = function () {
  21438. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21439. return;
  21440. }
  21441. // Sprites
  21442. var activeCamera = this._scene.activeCamera;
  21443. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21444. for (var id = 0; id < this._spriteManagers.length; id++) {
  21445. var spriteManager = this._spriteManagers.data[id];
  21446. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21447. spriteManager.render();
  21448. }
  21449. }
  21450. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21451. };
  21452. return RenderingGroup;
  21453. }());
  21454. BABYLON.RenderingGroup = RenderingGroup;
  21455. })(BABYLON || (BABYLON = {}));
  21456. //# sourceMappingURL=babylon.renderingGroup.js.map
  21457. "use strict";
  21458. var BABYLON;
  21459. (function (BABYLON) {
  21460. /** @ignore */
  21461. var ClickInfo = /** @class */ (function () {
  21462. function ClickInfo() {
  21463. this._singleClick = false;
  21464. this._doubleClick = false;
  21465. this._hasSwiped = false;
  21466. this._ignore = false;
  21467. }
  21468. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21469. get: function () {
  21470. return this._singleClick;
  21471. },
  21472. set: function (b) {
  21473. this._singleClick = b;
  21474. },
  21475. enumerable: true,
  21476. configurable: true
  21477. });
  21478. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21479. get: function () {
  21480. return this._doubleClick;
  21481. },
  21482. set: function (b) {
  21483. this._doubleClick = b;
  21484. },
  21485. enumerable: true,
  21486. configurable: true
  21487. });
  21488. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21489. get: function () {
  21490. return this._hasSwiped;
  21491. },
  21492. set: function (b) {
  21493. this._hasSwiped = b;
  21494. },
  21495. enumerable: true,
  21496. configurable: true
  21497. });
  21498. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21499. get: function () {
  21500. return this._ignore;
  21501. },
  21502. set: function (b) {
  21503. this._ignore = b;
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. return ClickInfo;
  21509. }());
  21510. /**
  21511. * This class is used by the onRenderingGroupObservable
  21512. */
  21513. var RenderingGroupInfo = /** @class */ (function () {
  21514. function RenderingGroupInfo() {
  21515. }
  21516. /**
  21517. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21518. * This stage will be fired no matter what
  21519. */
  21520. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21521. /**
  21522. * Called before opaque object are rendered.
  21523. * This stage will be fired only if there's 3D Opaque content to render
  21524. */
  21525. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21526. /**
  21527. * Called after the opaque objects are rendered and before the transparent ones
  21528. * This stage will be fired only if there's 3D transparent content to render
  21529. */
  21530. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21531. /**
  21532. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21533. * This stage will be fired no matter what
  21534. */
  21535. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21536. return RenderingGroupInfo;
  21537. }());
  21538. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21539. /**
  21540. * Represents a scene to be rendered by the engine.
  21541. * @see http://doc.babylonjs.com/features/scene
  21542. */
  21543. var Scene = /** @class */ (function () {
  21544. /**
  21545. * Creates a new Scene
  21546. * @param engine defines the engine to use to render this scene
  21547. */
  21548. function Scene(engine) {
  21549. // Members
  21550. /**
  21551. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  21552. */
  21553. this.autoClear = true;
  21554. /**
  21555. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  21556. */
  21557. this.autoClearDepthAndStencil = true;
  21558. /**
  21559. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  21560. */
  21561. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21562. /**
  21563. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  21564. */
  21565. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21566. this._forceWireframe = false;
  21567. this._forcePointsCloud = false;
  21568. /**
  21569. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  21570. */
  21571. this.forceShowBoundingBoxes = false;
  21572. /**
  21573. * Gets or sets a boolean indicating if animations are enabled
  21574. */
  21575. this.animationsEnabled = true;
  21576. /**
  21577. * Gets or sets a boolean indicating if a constant deltatime has to be used
  21578. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  21579. */
  21580. this.useConstantAnimationDeltaTime = false;
  21581. /**
  21582. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  21583. * Please note that it requires to run a ray cast through the scene on every frame
  21584. */
  21585. this.constantlyUpdateMeshUnderPointer = false;
  21586. /**
  21587. * Defines the HTML cursor to use when hovering over interactive elements
  21588. */
  21589. this.hoverCursor = "pointer";
  21590. /**
  21591. * Defines the HTML default cursor to use (empty by default)
  21592. */
  21593. this.defaultCursor = "";
  21594. /**
  21595. * This is used to call preventDefault() on pointer down
  21596. * in order to block unwanted artifacts like system double clicks
  21597. */
  21598. this.preventDefaultOnPointerDown = true;
  21599. // Metadata
  21600. /**
  21601. * Gets or sets user defined metadata
  21602. */
  21603. this.metadata = null;
  21604. /**
  21605. * Use this array to add regular expressions used to disable offline support for specific urls
  21606. */
  21607. this.disableOfflineSupportExceptionRules = new Array();
  21608. /**
  21609. * An event triggered when the scene is disposed.
  21610. */
  21611. this.onDisposeObservable = new BABYLON.Observable();
  21612. this._onDisposeObserver = null;
  21613. /**
  21614. * An event triggered before rendering the scene (right after animations and physics)
  21615. */
  21616. this.onBeforeRenderObservable = new BABYLON.Observable();
  21617. this._onBeforeRenderObserver = null;
  21618. /**
  21619. * An event triggered after rendering the scene
  21620. */
  21621. this.onAfterRenderObservable = new BABYLON.Observable();
  21622. this._onAfterRenderObserver = null;
  21623. /**
  21624. * An event triggered before animating the scene
  21625. */
  21626. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered after animations processing
  21629. */
  21630. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21631. /**
  21632. * An event triggered before draw calls are ready to be sent
  21633. */
  21634. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21635. /**
  21636. * An event triggered after draw calls have been sent
  21637. */
  21638. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21639. /**
  21640. * An event triggered when physic simulation is about to be run
  21641. */
  21642. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21643. /**
  21644. * An event triggered when physic simulation has been done
  21645. */
  21646. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21647. /**
  21648. * An event triggered when the scene is ready
  21649. */
  21650. this.onReadyObservable = new BABYLON.Observable();
  21651. /**
  21652. * An event triggered before rendering a camera
  21653. */
  21654. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21655. this._onBeforeCameraRenderObserver = null;
  21656. /**
  21657. * An event triggered after rendering a camera
  21658. */
  21659. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21660. this._onAfterCameraRenderObserver = null;
  21661. /**
  21662. * An event triggered when active meshes evaluation is about to start
  21663. */
  21664. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21665. /**
  21666. * An event triggered when active meshes evaluation is done
  21667. */
  21668. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21669. /**
  21670. * An event triggered when particles rendering is about to start
  21671. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21672. */
  21673. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21674. /**
  21675. * An event triggered when particles rendering is done
  21676. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21677. */
  21678. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21679. /**
  21680. * An event triggered when sprites rendering is about to start
  21681. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21682. */
  21683. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21684. /**
  21685. * An event triggered when sprites rendering is done
  21686. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21687. */
  21688. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21689. /**
  21690. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21691. */
  21692. this.onDataLoadedObservable = new BABYLON.Observable();
  21693. /**
  21694. * An event triggered when a camera is created
  21695. */
  21696. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21697. /**
  21698. * An event triggered when a camera is removed
  21699. */
  21700. this.onCameraRemovedObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered when a light is created
  21703. */
  21704. this.onNewLightAddedObservable = new BABYLON.Observable();
  21705. /**
  21706. * An event triggered when a light is removed
  21707. */
  21708. this.onLightRemovedObservable = new BABYLON.Observable();
  21709. /**
  21710. * An event triggered when a geometry is created
  21711. */
  21712. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21713. /**
  21714. * An event triggered when a geometry is removed
  21715. */
  21716. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21717. /**
  21718. * An event triggered when a transform node is created
  21719. */
  21720. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21721. /**
  21722. * An event triggered when a transform node is removed
  21723. */
  21724. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21725. /**
  21726. * An event triggered when a mesh is created
  21727. */
  21728. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21729. /**
  21730. * An event triggered when a mesh is removed
  21731. */
  21732. this.onMeshRemovedObservable = new BABYLON.Observable();
  21733. /**
  21734. * An event triggered when render targets are about to be rendered
  21735. * Can happen multiple times per frame.
  21736. */
  21737. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21738. /**
  21739. * An event triggered when render targets were rendered.
  21740. * Can happen multiple times per frame.
  21741. */
  21742. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21743. /**
  21744. * An event triggered before calculating deterministic simulation step
  21745. */
  21746. this.onBeforeStepObservable = new BABYLON.Observable();
  21747. /**
  21748. * An event triggered after calculating deterministic simulation step
  21749. */
  21750. this.onAfterStepObservable = new BABYLON.Observable();
  21751. /**
  21752. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21753. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21754. * 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)
  21755. */
  21756. this.onRenderingGroupObservable = new BABYLON.Observable();
  21757. // Animations
  21758. /**
  21759. * Gets a list of Animations associated with the scene
  21760. */
  21761. this.animations = [];
  21762. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21763. /**
  21764. * 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).
  21765. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21766. */
  21767. this.onPrePointerObservable = new BABYLON.Observable();
  21768. /**
  21769. * Observable event triggered each time an input event is received from the rendering canvas
  21770. */
  21771. this.onPointerObservable = new BABYLON.Observable();
  21772. this._meshPickProceed = false;
  21773. this._currentPickResult = null;
  21774. this._previousPickResult = null;
  21775. this._totalPointersPressed = 0;
  21776. this._doubleClickOccured = false;
  21777. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21778. this.cameraToUseForPointers = null;
  21779. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21780. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21781. this._startingPointerTime = 0;
  21782. this._previousStartingPointerTime = 0;
  21783. // Deterministic lockstep
  21784. this._timeAccumulator = 0;
  21785. this._currentStepId = 0;
  21786. this._currentInternalStep = 0;
  21787. // Keyboard
  21788. /**
  21789. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21790. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21791. */
  21792. this.onPreKeyboardObservable = new BABYLON.Observable();
  21793. /**
  21794. * Observable event triggered each time an keyboard event is received from the hosting window
  21795. */
  21796. this.onKeyboardObservable = new BABYLON.Observable();
  21797. // Coordinates system
  21798. this._useRightHandedSystem = false;
  21799. // Fog
  21800. this._fogEnabled = true;
  21801. this._fogMode = Scene.FOGMODE_NONE;
  21802. /**
  21803. * Gets or sets the fog color to use
  21804. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21805. */
  21806. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21807. /**
  21808. * Gets or sets the fog density to use
  21809. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21810. */
  21811. this.fogDensity = 0.1;
  21812. /**
  21813. * Gets or sets the fog start distance to use
  21814. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21815. */
  21816. this.fogStart = 0;
  21817. /**
  21818. * Gets or sets the fog end distance to use
  21819. * @see http://doc.babylonjs.com/babylon101/environment#fog
  21820. */
  21821. this.fogEnd = 1000.0;
  21822. // Lights
  21823. this._shadowsEnabled = true;
  21824. this._lightsEnabled = true;
  21825. /**
  21826. * All of the lights added to this scene
  21827. * @see http://doc.babylonjs.com/babylon101/lights
  21828. */
  21829. this.lights = new Array();
  21830. // Cameras
  21831. /** All of the cameras added to this scene.
  21832. * @see http://doc.babylonjs.com/babylon101/cameras
  21833. */
  21834. this.cameras = new Array();
  21835. /** All of the active cameras added to this scene. */
  21836. this.activeCameras = new Array();
  21837. // Meshes
  21838. /**
  21839. * All of the tranform nodes added to this scene
  21840. * @see http://doc.babylonjs.com/how_to/transformnode
  21841. */
  21842. this.transformNodes = new Array();
  21843. /**
  21844. * All of the (abstract) meshes added to this scene
  21845. */
  21846. this.meshes = new Array();
  21847. /**
  21848. * All of the animation groups added to this scene
  21849. * @see http://doc.babylonjs.com/how_to/group
  21850. */
  21851. this.animationGroups = new Array();
  21852. // Geometries
  21853. this._geometries = new Array();
  21854. /**
  21855. * All of the materials added to this scene
  21856. * @see http://doc.babylonjs.com/babylon101/materials
  21857. */
  21858. this.materials = new Array();
  21859. /**
  21860. * All of the multi-materials added to this scene
  21861. * @see http://doc.babylonjs.com/how_to/multi_materials
  21862. */
  21863. this.multiMaterials = new Array();
  21864. // Textures
  21865. this._texturesEnabled = true;
  21866. /**
  21867. * All of the textures added to this scene
  21868. */
  21869. this.textures = new Array();
  21870. // Particles
  21871. /**
  21872. * Gets or sets a boolean indicating if particles are enabled on this scene
  21873. */
  21874. this.particlesEnabled = true;
  21875. /**
  21876. * All of the particle systems added to this scene
  21877. * @see http://doc.babylonjs.com/babylon101/particles
  21878. */
  21879. this.particleSystems = new Array();
  21880. // Sprites
  21881. /**
  21882. * Gets or sets a boolean indicating if sprites are enabled on this scene
  21883. */
  21884. this.spritesEnabled = true;
  21885. /**
  21886. * All of the sprite managers added to this scene
  21887. * @see http://doc.babylonjs.com/babylon101/sprites
  21888. */
  21889. this.spriteManagers = new Array();
  21890. /**
  21891. * The list of layers (background and foreground) of the scene
  21892. */
  21893. this.layers = new Array();
  21894. /**
  21895. * The list of effect layers (highlights/glow) added to the scene
  21896. * @see http://doc.babylonjs.com/how_to/highlight_layer
  21897. * @see http://doc.babylonjs.com/how_to/glow_layer
  21898. */
  21899. this.effectLayers = new Array();
  21900. // Skeletons
  21901. this._skeletonsEnabled = true;
  21902. /**
  21903. * The list of skeletons added to the scene
  21904. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21905. */
  21906. this.skeletons = new Array();
  21907. // Morph targets
  21908. /**
  21909. * The list of morph target managers added to the scene
  21910. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  21911. */
  21912. this.morphTargetManagers = new Array();
  21913. // Lens flares
  21914. /**
  21915. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  21916. */
  21917. this.lensFlaresEnabled = true;
  21918. /**
  21919. * The list of lens flare system added to the scene
  21920. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  21921. */
  21922. this.lensFlareSystems = new Array();
  21923. // Collisions
  21924. /**
  21925. * Gets or sets a boolean indicating if collisions are enabled on this scene
  21926. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21927. */
  21928. this.collisionsEnabled = true;
  21929. /**
  21930. * Defines the gravity applied to this scene (used only for collisions)
  21931. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21932. */
  21933. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21934. // Postprocesses
  21935. /**
  21936. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  21937. */
  21938. this.postProcessesEnabled = true;
  21939. /**
  21940. * The list of postprocesses added to the scene
  21941. */
  21942. this.postProcesses = new Array();
  21943. // Customs render targets
  21944. /**
  21945. * Gets or sets a boolean indicating if render targets are enabled on this scene
  21946. */
  21947. this.renderTargetsEnabled = true;
  21948. /**
  21949. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  21950. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  21951. */
  21952. this.dumpNextRenderTargets = false;
  21953. /**
  21954. * The list of user defined render targets added to the scene
  21955. */
  21956. this.customRenderTargets = new Array();
  21957. /**
  21958. * Gets the list of meshes imported to the scene through SceneLoader
  21959. */
  21960. this.importedMeshesFiles = new Array();
  21961. // Probes
  21962. /**
  21963. * Gets or sets a boolean indicating if probes are enabled on this scene
  21964. */
  21965. this.probesEnabled = true;
  21966. /**
  21967. * The list of reflection probes added to the scene
  21968. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  21969. */
  21970. this.reflectionProbes = new Array();
  21971. /** @ignore */
  21972. this._actionManagers = new Array();
  21973. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21974. // Procedural textures
  21975. /**
  21976. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  21977. */
  21978. this.proceduralTexturesEnabled = true;
  21979. /**
  21980. * The list of procedural textures added to the scene
  21981. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  21982. */
  21983. this.proceduralTextures = new Array();
  21984. /**
  21985. * The list of sound tracks added to the scene
  21986. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  21987. */
  21988. this.soundTracks = new Array();
  21989. this._audioEnabled = true;
  21990. this._headphone = false;
  21991. // Performance counters
  21992. this._totalVertices = new BABYLON.PerfCounter();
  21993. /** @ignore */
  21994. this._activeIndices = new BABYLON.PerfCounter();
  21995. /** @ignore */
  21996. this._activeParticles = new BABYLON.PerfCounter();
  21997. /** @ignore */
  21998. this._activeBones = new BABYLON.PerfCounter();
  21999. this._animationTime = 0;
  22000. /**
  22001. * Gets or sets a general scale for animation speed
  22002. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  22003. */
  22004. this.animationTimeScale = 1;
  22005. this._renderId = 0;
  22006. this._executeWhenReadyTimeoutId = -1;
  22007. this._intermediateRendering = false;
  22008. this._viewUpdateFlag = -1;
  22009. this._projectionUpdateFlag = -1;
  22010. this._alternateViewUpdateFlag = -1;
  22011. this._alternateProjectionUpdateFlag = -1;
  22012. /** @ignore */
  22013. this._toBeDisposed = new BABYLON.SmartArray(256);
  22014. this._activeRequests = new Array();
  22015. this._pendingData = new Array();
  22016. this._isDisposed = false;
  22017. /**
  22018. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  22019. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  22020. */
  22021. this.dispatchAllSubMeshesOfActiveMeshes = false;
  22022. this._activeMeshes = new BABYLON.SmartArray(256);
  22023. this._processedMaterials = new BABYLON.SmartArray(256);
  22024. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  22025. /** @ignore */
  22026. this._activeParticleSystems = new BABYLON.SmartArray(256);
  22027. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  22028. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  22029. /** @ignore */
  22030. this._activeAnimatables = new Array();
  22031. this._transformMatrix = BABYLON.Matrix.Zero();
  22032. this._useAlternateCameraConfiguration = false;
  22033. this._alternateRendering = false;
  22034. /**
  22035. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  22036. * This is useful if there are more lights that the maximum simulteanous authorized
  22037. */
  22038. this.requireLightSorting = false;
  22039. this._depthRenderer = {};
  22040. this._activeMeshesFrozen = false;
  22041. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  22042. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  22043. this._engine.scenes.push(this);
  22044. this._uid = null;
  22045. this._renderingManager = new BABYLON.RenderingManager(this);
  22046. this.postProcessManager = new BABYLON.PostProcessManager(this);
  22047. if (BABYLON.OutlineRenderer) {
  22048. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  22049. }
  22050. if (BABYLON.Tools.IsWindowObjectExist()) {
  22051. this.attachControl();
  22052. }
  22053. //simplification queue
  22054. if (BABYLON.SimplificationQueue) {
  22055. this.simplificationQueue = new BABYLON.SimplificationQueue();
  22056. }
  22057. //collision coordinator initialization. For now legacy per default.
  22058. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  22059. // Uniform Buffer
  22060. this._createUbo();
  22061. // Default Image processing definition.
  22062. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  22063. }
  22064. Object.defineProperty(Scene, "FOGMODE_NONE", {
  22065. /** The fog is deactivated */
  22066. get: function () {
  22067. return Scene._FOGMODE_NONE;
  22068. },
  22069. enumerable: true,
  22070. configurable: true
  22071. });
  22072. Object.defineProperty(Scene, "FOGMODE_EXP", {
  22073. /** The fog density is following an exponential function */
  22074. get: function () {
  22075. return Scene._FOGMODE_EXP;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  22081. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  22082. get: function () {
  22083. return Scene._FOGMODE_EXP2;
  22084. },
  22085. enumerable: true,
  22086. configurable: true
  22087. });
  22088. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  22089. /** The fog density is following a linear function. */
  22090. get: function () {
  22091. return Scene._FOGMODE_LINEAR;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Scene.prototype, "environmentTexture", {
  22097. /**
  22098. * Texture used in all pbr material as the reflection texture.
  22099. * As in the majority of the scene they are the same (exception for multi room and so on),
  22100. * this is easier to reference from here than from all the materials.
  22101. */
  22102. get: function () {
  22103. return this._environmentTexture;
  22104. },
  22105. /**
  22106. * Texture used in all pbr material as the reflection texture.
  22107. * As in the majority of the scene they are the same (exception for multi room and so on),
  22108. * this is easier to set here than in all the materials.
  22109. */
  22110. set: function (value) {
  22111. if (this._environmentTexture === value) {
  22112. return;
  22113. }
  22114. this._environmentTexture = value;
  22115. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22116. },
  22117. enumerable: true,
  22118. configurable: true
  22119. });
  22120. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22121. /**
  22122. * Default image processing configuration used either in the rendering
  22123. * Forward main pass or through the imageProcessingPostProcess if present.
  22124. * As in the majority of the scene they are the same (exception for multi camera),
  22125. * this is easier to reference from here than from all the materials and post process.
  22126. *
  22127. * No setter as we it is a shared configuration, you can set the values instead.
  22128. */
  22129. get: function () {
  22130. return this._imageProcessingConfiguration;
  22131. },
  22132. enumerable: true,
  22133. configurable: true
  22134. });
  22135. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22136. get: function () {
  22137. return this._forceWireframe;
  22138. },
  22139. /**
  22140. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  22141. */
  22142. set: function (value) {
  22143. if (this._forceWireframe === value) {
  22144. return;
  22145. }
  22146. this._forceWireframe = value;
  22147. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22148. },
  22149. enumerable: true,
  22150. configurable: true
  22151. });
  22152. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22153. get: function () {
  22154. return this._forcePointsCloud;
  22155. },
  22156. /**
  22157. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  22158. */
  22159. set: function (value) {
  22160. if (this._forcePointsCloud === value) {
  22161. return;
  22162. }
  22163. this._forcePointsCloud = value;
  22164. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22165. },
  22166. enumerable: true,
  22167. configurable: true
  22168. });
  22169. Object.defineProperty(Scene.prototype, "onDispose", {
  22170. /** Sets a function to be executed when this scene is disposed. */
  22171. set: function (callback) {
  22172. if (this._onDisposeObserver) {
  22173. this.onDisposeObservable.remove(this._onDisposeObserver);
  22174. }
  22175. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22176. },
  22177. enumerable: true,
  22178. configurable: true
  22179. });
  22180. Object.defineProperty(Scene.prototype, "beforeRender", {
  22181. /** Sets a function to be executed before rendering this scene */
  22182. set: function (callback) {
  22183. if (this._onBeforeRenderObserver) {
  22184. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22185. }
  22186. if (callback) {
  22187. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22188. }
  22189. },
  22190. enumerable: true,
  22191. configurable: true
  22192. });
  22193. Object.defineProperty(Scene.prototype, "afterRender", {
  22194. /** Sets a function to be executed after rendering this scene */
  22195. set: function (callback) {
  22196. if (this._onAfterRenderObserver) {
  22197. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22198. }
  22199. if (callback) {
  22200. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22201. }
  22202. },
  22203. enumerable: true,
  22204. configurable: true
  22205. });
  22206. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22207. /** Sets a function to be executed before rendering a camera*/
  22208. set: function (callback) {
  22209. if (this._onBeforeCameraRenderObserver) {
  22210. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22211. }
  22212. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22213. },
  22214. enumerable: true,
  22215. configurable: true
  22216. });
  22217. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22218. /** Sets a function to be executed after rendering a camera*/
  22219. set: function (callback) {
  22220. if (this._onAfterCameraRenderObserver) {
  22221. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22222. }
  22223. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22224. },
  22225. enumerable: true,
  22226. configurable: true
  22227. });
  22228. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22229. /**
  22230. * Gets the gamepad manager associated with the scene
  22231. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  22232. */
  22233. get: function () {
  22234. if (!this._gamepadManager) {
  22235. this._gamepadManager = new BABYLON.GamepadManager(this);
  22236. }
  22237. return this._gamepadManager;
  22238. },
  22239. enumerable: true,
  22240. configurable: true
  22241. });
  22242. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22243. /**
  22244. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  22245. */
  22246. get: function () {
  22247. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22253. get: function () {
  22254. return this._useRightHandedSystem;
  22255. },
  22256. /**
  22257. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  22258. */
  22259. set: function (value) {
  22260. if (this._useRightHandedSystem === value) {
  22261. return;
  22262. }
  22263. this._useRightHandedSystem = value;
  22264. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. /**
  22270. * Sets the step Id used by deterministic lock step
  22271. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  22272. * @param newStepId defines the step Id
  22273. */
  22274. Scene.prototype.setStepId = function (newStepId) {
  22275. this._currentStepId = newStepId;
  22276. };
  22277. ;
  22278. /**
  22279. * Gets the step Id used by deterministic lock step
  22280. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  22281. * @returns the step Id
  22282. */
  22283. Scene.prototype.getStepId = function () {
  22284. return this._currentStepId;
  22285. };
  22286. ;
  22287. /**
  22288. * Gets the internal step used by deterministic lock step
  22289. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  22290. * @returns the internal step
  22291. */
  22292. Scene.prototype.getInternalStep = function () {
  22293. return this._currentInternalStep;
  22294. };
  22295. ;
  22296. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22297. get: function () {
  22298. return this._fogEnabled;
  22299. },
  22300. /**
  22301. * Gets or sets a boolean indicating if fog is enabled on this scene
  22302. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22303. */
  22304. set: function (value) {
  22305. if (this._fogEnabled === value) {
  22306. return;
  22307. }
  22308. this._fogEnabled = value;
  22309. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22310. },
  22311. enumerable: true,
  22312. configurable: true
  22313. });
  22314. Object.defineProperty(Scene.prototype, "fogMode", {
  22315. get: function () {
  22316. return this._fogMode;
  22317. },
  22318. /**
  22319. * Gets or sets the fog mode to use
  22320. * @see http://doc.babylonjs.com/babylon101/environment#fog
  22321. */
  22322. set: function (value) {
  22323. if (this._fogMode === value) {
  22324. return;
  22325. }
  22326. this._fogMode = value;
  22327. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22328. },
  22329. enumerable: true,
  22330. configurable: true
  22331. });
  22332. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22333. get: function () {
  22334. return this._shadowsEnabled;
  22335. },
  22336. /**
  22337. * Gets or sets a boolean indicating if shadows are enabled on this scene
  22338. */
  22339. set: function (value) {
  22340. if (this._shadowsEnabled === value) {
  22341. return;
  22342. }
  22343. this._shadowsEnabled = value;
  22344. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22345. },
  22346. enumerable: true,
  22347. configurable: true
  22348. });
  22349. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22350. get: function () {
  22351. return this._lightsEnabled;
  22352. },
  22353. /**
  22354. * Gets or sets a boolean indicating if lights are enabled on this scene
  22355. */
  22356. set: function (value) {
  22357. if (this._lightsEnabled === value) {
  22358. return;
  22359. }
  22360. this._lightsEnabled = value;
  22361. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22367. /** The default material used on meshes when no material is affected */
  22368. get: function () {
  22369. if (!this._defaultMaterial) {
  22370. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22371. }
  22372. return this._defaultMaterial;
  22373. },
  22374. /** The default material used on meshes when no material is affected */
  22375. set: function (value) {
  22376. this._defaultMaterial = value;
  22377. },
  22378. enumerable: true,
  22379. configurable: true
  22380. });
  22381. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22382. get: function () {
  22383. return this._texturesEnabled;
  22384. },
  22385. /**
  22386. * Gets or sets a boolean indicating if textures are enabled on this scene
  22387. */
  22388. set: function (value) {
  22389. if (this._texturesEnabled === value) {
  22390. return;
  22391. }
  22392. this._texturesEnabled = value;
  22393. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22394. },
  22395. enumerable: true,
  22396. configurable: true
  22397. });
  22398. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22399. get: function () {
  22400. return this._skeletonsEnabled;
  22401. },
  22402. /**
  22403. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  22404. */
  22405. set: function (value) {
  22406. if (this._skeletonsEnabled === value) {
  22407. return;
  22408. }
  22409. this._skeletonsEnabled = value;
  22410. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22416. /**
  22417. * Gets the postprocess render pipeline manager
  22418. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  22419. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  22420. */
  22421. get: function () {
  22422. if (!this._postProcessRenderPipelineManager) {
  22423. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22424. }
  22425. return this._postProcessRenderPipelineManager;
  22426. },
  22427. enumerable: true,
  22428. configurable: true
  22429. });
  22430. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22431. /**
  22432. * Gets the main soundtrack associated with the scene
  22433. */
  22434. get: function () {
  22435. if (!this._mainSoundTrack) {
  22436. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22437. }
  22438. return this._mainSoundTrack;
  22439. },
  22440. enumerable: true,
  22441. configurable: true
  22442. });
  22443. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22444. /** @ignore */
  22445. get: function () {
  22446. return this._alternateRendering;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22452. /**
  22453. * Gets the list of frustum planes (built from the active camera)
  22454. */
  22455. get: function () {
  22456. return this._frustumPlanes;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22462. /**
  22463. * Gets the current geometry buffer associated to the scene.
  22464. */
  22465. get: function () {
  22466. return this._geometryBufferRenderer;
  22467. },
  22468. /**
  22469. * Sets the current geometry buffer for the scene.
  22470. */
  22471. set: function (geometryBufferRenderer) {
  22472. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22473. this._geometryBufferRenderer = geometryBufferRenderer;
  22474. }
  22475. },
  22476. enumerable: true,
  22477. configurable: true
  22478. });
  22479. Object.defineProperty(Scene.prototype, "debugLayer", {
  22480. /**
  22481. * Gets the debug layer associated with the scene
  22482. * @see http://doc.babylonjs.com/features/playground_debuglayer
  22483. */
  22484. get: function () {
  22485. if (!this._debugLayer) {
  22486. this._debugLayer = new BABYLON.DebugLayer(this);
  22487. }
  22488. return this._debugLayer;
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22494. /**
  22495. * Gets a boolean indicating if collisions are processed on a web worker
  22496. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  22497. */
  22498. get: function () {
  22499. return this._workerCollisions;
  22500. },
  22501. set: function (enabled) {
  22502. if (!BABYLON.CollisionCoordinatorLegacy) {
  22503. return;
  22504. }
  22505. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22506. this._workerCollisions = enabled;
  22507. if (this.collisionCoordinator) {
  22508. this.collisionCoordinator.destroy();
  22509. }
  22510. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22511. this.collisionCoordinator.init(this);
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22517. /**
  22518. * Gets the octree used to boost mesh selection (picking)
  22519. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  22520. */
  22521. get: function () {
  22522. return this._selectionOctree;
  22523. },
  22524. enumerable: true,
  22525. configurable: true
  22526. });
  22527. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22528. /**
  22529. * Gets the mesh that is currently under the pointer
  22530. */
  22531. get: function () {
  22532. return this._pointerOverMesh;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. Object.defineProperty(Scene.prototype, "pointerX", {
  22538. /**
  22539. * Gets the current on-screen X position of the pointer
  22540. */
  22541. get: function () {
  22542. return this._pointerX;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Object.defineProperty(Scene.prototype, "pointerY", {
  22548. /**
  22549. * Gets the current on-screen Y position of the pointer
  22550. */
  22551. get: function () {
  22552. return this._pointerY;
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. /**
  22558. * Gets the cached material (ie. the latest rendered one)
  22559. * @returns the cached material
  22560. */
  22561. Scene.prototype.getCachedMaterial = function () {
  22562. return this._cachedMaterial;
  22563. };
  22564. /**
  22565. * Gets the cached effect (ie. the latest rendered one)
  22566. * @returns the cached effect
  22567. */
  22568. Scene.prototype.getCachedEffect = function () {
  22569. return this._cachedEffect;
  22570. };
  22571. /**
  22572. * Gets the cached visibility state (ie. the latest rendered one)
  22573. * @returns the cached visibility state
  22574. */
  22575. Scene.prototype.getCachedVisibility = function () {
  22576. return this._cachedVisibility;
  22577. };
  22578. /**
  22579. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  22580. * @param material defines the current material
  22581. * @param effect defines the current effect
  22582. * @param visibility defines the current visibility state
  22583. * @returns true if one parameter is not cached
  22584. */
  22585. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22586. if (visibility === void 0) { visibility = 1; }
  22587. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22588. };
  22589. /**
  22590. * Gets the bounding box renderer associated with the scene
  22591. * @returns a BoundingBoxRenderer
  22592. */
  22593. Scene.prototype.getBoundingBoxRenderer = function () {
  22594. if (!this._boundingBoxRenderer) {
  22595. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22596. }
  22597. return this._boundingBoxRenderer;
  22598. };
  22599. /**
  22600. * Gets the outline renderer associated with the scene
  22601. * @returns a OutlineRenderer
  22602. */
  22603. Scene.prototype.getOutlineRenderer = function () {
  22604. return this._outlineRenderer;
  22605. };
  22606. /**
  22607. * Gets the engine associated with the scene
  22608. * @returns an Engine
  22609. */
  22610. Scene.prototype.getEngine = function () {
  22611. return this._engine;
  22612. };
  22613. /**
  22614. * Gets the total number of vertices rendered per frame
  22615. * @returns the total number of vertices rendered per frame
  22616. */
  22617. Scene.prototype.getTotalVertices = function () {
  22618. return this._totalVertices.current;
  22619. };
  22620. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22621. /**
  22622. * Gets the performance counter for total vertices
  22623. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22624. */
  22625. get: function () {
  22626. return this._totalVertices;
  22627. },
  22628. enumerable: true,
  22629. configurable: true
  22630. });
  22631. /**
  22632. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  22633. * @returns the total number of active indices rendered per frame
  22634. */
  22635. Scene.prototype.getActiveIndices = function () {
  22636. return this._activeIndices.current;
  22637. };
  22638. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22639. /**
  22640. * Gets the performance counter for active indices
  22641. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22642. */
  22643. get: function () {
  22644. return this._activeIndices;
  22645. },
  22646. enumerable: true,
  22647. configurable: true
  22648. });
  22649. /**
  22650. * Gets the total number of active particles rendered per frame
  22651. * @returns the total number of active particles rendered per frame
  22652. */
  22653. Scene.prototype.getActiveParticles = function () {
  22654. return this._activeParticles.current;
  22655. };
  22656. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22657. /**
  22658. * Gets the performance counter for active particles
  22659. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22660. */
  22661. get: function () {
  22662. return this._activeParticles;
  22663. },
  22664. enumerable: true,
  22665. configurable: true
  22666. });
  22667. /**
  22668. * Gets the total number of active bones rendered per frame
  22669. * @returns the total number of active bones rendered per frame
  22670. */
  22671. Scene.prototype.getActiveBones = function () {
  22672. return this._activeBones.current;
  22673. };
  22674. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22675. /**
  22676. * Gets the performance counter for active bones
  22677. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  22678. */
  22679. get: function () {
  22680. return this._activeBones;
  22681. },
  22682. enumerable: true,
  22683. configurable: true
  22684. });
  22685. /** @ignore */
  22686. Scene.prototype.getInterFramePerfCounter = function () {
  22687. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22688. return 0;
  22689. };
  22690. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22691. /** @ignore */
  22692. get: function () {
  22693. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22694. return null;
  22695. },
  22696. enumerable: true,
  22697. configurable: true
  22698. });
  22699. /** @ignore */
  22700. Scene.prototype.getLastFrameDuration = function () {
  22701. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22702. return 0;
  22703. };
  22704. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22705. /** @ignore */
  22706. get: function () {
  22707. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22708. return null;
  22709. },
  22710. enumerable: true,
  22711. configurable: true
  22712. });
  22713. /** @ignore */
  22714. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22715. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22716. return 0;
  22717. };
  22718. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22719. /** @ignore */
  22720. get: function () {
  22721. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22722. return null;
  22723. },
  22724. enumerable: true,
  22725. configurable: true
  22726. });
  22727. /**
  22728. * Gets the array of active meshes
  22729. * @returns an array of AbstractMesh
  22730. */
  22731. Scene.prototype.getActiveMeshes = function () {
  22732. return this._activeMeshes;
  22733. };
  22734. /** @ignore */
  22735. Scene.prototype.getRenderTargetsDuration = function () {
  22736. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22737. return 0;
  22738. };
  22739. /** @ignore */
  22740. Scene.prototype.getRenderDuration = function () {
  22741. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22742. return 0;
  22743. };
  22744. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22745. /** @ignore */
  22746. get: function () {
  22747. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22748. return null;
  22749. },
  22750. enumerable: true,
  22751. configurable: true
  22752. });
  22753. /** @ignore */
  22754. Scene.prototype.getParticlesDuration = function () {
  22755. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22756. return 0;
  22757. };
  22758. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22759. /** @ignore */
  22760. get: function () {
  22761. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22762. return null;
  22763. },
  22764. enumerable: true,
  22765. configurable: true
  22766. });
  22767. /** @ignore */
  22768. Scene.prototype.getSpritesDuration = function () {
  22769. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22770. return 0;
  22771. };
  22772. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22773. /** @ignore */
  22774. get: function () {
  22775. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22776. return null;
  22777. },
  22778. enumerable: true,
  22779. configurable: true
  22780. });
  22781. /**
  22782. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  22783. * @returns a number
  22784. */
  22785. Scene.prototype.getAnimationRatio = function () {
  22786. return this._animationRatio;
  22787. };
  22788. /**
  22789. * Gets an unique Id for the current frame
  22790. * @returns a number
  22791. */
  22792. Scene.prototype.getRenderId = function () {
  22793. return this._renderId;
  22794. };
  22795. /** Call this function if you want to manually increment the render Id*/
  22796. Scene.prototype.incrementRenderId = function () {
  22797. this._renderId++;
  22798. };
  22799. Scene.prototype._updatePointerPosition = function (evt) {
  22800. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22801. if (!canvasRect) {
  22802. return;
  22803. }
  22804. this._pointerX = evt.clientX - canvasRect.left;
  22805. this._pointerY = evt.clientY - canvasRect.top;
  22806. this._unTranslatedPointerX = this._pointerX;
  22807. this._unTranslatedPointerY = this._pointerY;
  22808. };
  22809. Scene.prototype._createUbo = function () {
  22810. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22811. this._sceneUbo.addUniform("viewProjection", 16);
  22812. this._sceneUbo.addUniform("view", 16);
  22813. };
  22814. Scene.prototype._createAlternateUbo = function () {
  22815. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22816. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22817. this._alternateSceneUbo.addUniform("view", 16);
  22818. };
  22819. // Pointers handling
  22820. /**
  22821. * Use this method to simulate a pointer move on a mesh
  22822. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22823. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22824. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22825. * @returns the current scene
  22826. */
  22827. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22828. var evt = new PointerEvent("pointermove", pointerEventInit);
  22829. return this._processPointerMove(pickResult, evt);
  22830. };
  22831. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22832. var canvas = this._engine.getRenderingCanvas();
  22833. if (!canvas) {
  22834. return this;
  22835. }
  22836. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22837. this.setPointerOverSprite(null);
  22838. this.setPointerOverMesh(pickResult.pickedMesh);
  22839. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22840. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22841. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22842. }
  22843. else {
  22844. canvas.style.cursor = this.hoverCursor;
  22845. }
  22846. }
  22847. else {
  22848. canvas.style.cursor = this.defaultCursor;
  22849. }
  22850. }
  22851. else {
  22852. this.setPointerOverMesh(null);
  22853. // Sprites
  22854. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22855. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22856. this.setPointerOverSprite(pickResult.pickedSprite);
  22857. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22858. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22859. }
  22860. else {
  22861. canvas.style.cursor = this.hoverCursor;
  22862. }
  22863. }
  22864. else {
  22865. this.setPointerOverSprite(null);
  22866. // Restore pointer
  22867. canvas.style.cursor = this.defaultCursor;
  22868. }
  22869. }
  22870. if (pickResult) {
  22871. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22872. if (this.onPointerMove) {
  22873. this.onPointerMove(evt, pickResult, type);
  22874. }
  22875. if (this.onPointerObservable.hasObservers()) {
  22876. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22877. this.onPointerObservable.notifyObservers(pi, type);
  22878. }
  22879. }
  22880. return this;
  22881. };
  22882. /**
  22883. * Use this method to simulate a pointer down on a mesh
  22884. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22885. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22886. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22887. * @returns the current scene
  22888. */
  22889. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22890. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22891. return this._processPointerDown(pickResult, evt);
  22892. };
  22893. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22894. var _this = this;
  22895. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22896. this._pickedDownMesh = pickResult.pickedMesh;
  22897. var actionManager = pickResult.pickedMesh.actionManager;
  22898. if (actionManager) {
  22899. if (actionManager.hasPickTriggers) {
  22900. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22901. switch (evt.button) {
  22902. case 0:
  22903. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22904. break;
  22905. case 1:
  22906. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22907. break;
  22908. case 2:
  22909. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22910. break;
  22911. }
  22912. }
  22913. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22914. window.setTimeout(function () {
  22915. 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);
  22916. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22917. if (_this._totalPointersPressed !== 0 &&
  22918. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22919. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22920. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22921. _this._startingPointerTime = 0;
  22922. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22923. }
  22924. }
  22925. }, Scene.LongPressDelay);
  22926. }
  22927. }
  22928. }
  22929. if (pickResult) {
  22930. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22931. if (this.onPointerDown) {
  22932. this.onPointerDown(evt, pickResult, type);
  22933. }
  22934. if (this.onPointerObservable.hasObservers()) {
  22935. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22936. this.onPointerObservable.notifyObservers(pi, type);
  22937. }
  22938. }
  22939. return this;
  22940. };
  22941. /**
  22942. * Use this method to simulate a pointer up on a mesh
  22943. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22944. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22945. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22946. * @returns the current scene
  22947. */
  22948. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22949. var evt = new PointerEvent("pointerup", pointerEventInit);
  22950. var clickInfo = new ClickInfo();
  22951. clickInfo.singleClick = true;
  22952. clickInfo.ignore = true;
  22953. return this._processPointerUp(pickResult, evt, clickInfo);
  22954. };
  22955. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22956. if (pickResult && pickResult && pickResult.pickedMesh) {
  22957. this._pickedUpMesh = pickResult.pickedMesh;
  22958. if (this._pickedDownMesh === this._pickedUpMesh) {
  22959. if (this.onPointerPick) {
  22960. this.onPointerPick(evt, pickResult);
  22961. }
  22962. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22963. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22964. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22965. this.onPointerObservable.notifyObservers(pi, type_1);
  22966. }
  22967. }
  22968. if (pickResult.pickedMesh.actionManager) {
  22969. if (clickInfo.ignore) {
  22970. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22971. }
  22972. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22973. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22974. }
  22975. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22976. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22977. }
  22978. }
  22979. }
  22980. if (this._pickedDownMesh &&
  22981. this._pickedDownMesh.actionManager &&
  22982. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22983. this._pickedDownMesh !== this._pickedUpMesh) {
  22984. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22985. }
  22986. var type = BABYLON.PointerEventTypes.POINTERUP;
  22987. if (this.onPointerObservable.hasObservers()) {
  22988. if (!clickInfo.ignore) {
  22989. if (!clickInfo.hasSwiped) {
  22990. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22991. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22992. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22993. this.onPointerObservable.notifyObservers(pi, type_2);
  22994. }
  22995. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22996. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22997. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22998. this.onPointerObservable.notifyObservers(pi, type_3);
  22999. }
  23000. }
  23001. }
  23002. else {
  23003. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  23004. this.onPointerObservable.notifyObservers(pi, type);
  23005. }
  23006. }
  23007. if (this.onPointerUp) {
  23008. this.onPointerUp(evt, pickResult, type);
  23009. }
  23010. return this;
  23011. };
  23012. /**
  23013. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  23014. * @param attachUp defines if you want to attach events to pointerup
  23015. * @param attachDown defines if you want to attach events to pointerdown
  23016. * @param attachMove defines if you want to attach events to pointermove
  23017. */
  23018. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  23019. var _this = this;
  23020. if (attachUp === void 0) { attachUp = true; }
  23021. if (attachDown === void 0) { attachDown = true; }
  23022. if (attachMove === void 0) { attachMove = true; }
  23023. this._initActionManager = function (act, clickInfo) {
  23024. if (!_this._meshPickProceed) {
  23025. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23026. _this._currentPickResult = pickResult;
  23027. if (pickResult) {
  23028. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  23029. }
  23030. _this._meshPickProceed = true;
  23031. }
  23032. return act;
  23033. };
  23034. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  23035. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  23036. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  23037. btn !== _this._previousButtonPressed) {
  23038. _this._doubleClickOccured = false;
  23039. clickInfo.singleClick = true;
  23040. clickInfo.ignore = false;
  23041. cb(clickInfo, _this._currentPickResult);
  23042. }
  23043. };
  23044. this._initClickEvent = function (obs1, obs2, evt, cb) {
  23045. var clickInfo = new ClickInfo();
  23046. _this._currentPickResult = null;
  23047. var act = null;
  23048. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  23049. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  23050. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  23051. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  23052. act = _this._initActionManager(act, clickInfo);
  23053. if (act)
  23054. checkPicking = act.hasPickTriggers;
  23055. }
  23056. if (checkPicking) {
  23057. var btn = evt.button;
  23058. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  23059. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  23060. if (!clickInfo.hasSwiped) {
  23061. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  23062. if (!checkSingleClickImmediately) {
  23063. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  23064. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  23065. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  23066. act = _this._initActionManager(act, clickInfo);
  23067. if (act)
  23068. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  23069. }
  23070. }
  23071. if (checkSingleClickImmediately) {
  23072. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  23073. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  23074. btn !== _this._previousButtonPressed) {
  23075. clickInfo.singleClick = true;
  23076. cb(clickInfo, _this._currentPickResult);
  23077. }
  23078. }
  23079. else {
  23080. // wait that no double click has been raised during the double click delay
  23081. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  23082. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  23083. }
  23084. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  23085. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  23086. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  23087. act = _this._initActionManager(act, clickInfo);
  23088. if (act)
  23089. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  23090. }
  23091. if (checkDoubleClick) {
  23092. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  23093. if (btn === _this._previousButtonPressed &&
  23094. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  23095. !_this._doubleClickOccured) {
  23096. // pointer has not moved for 2 clicks, it's a double click
  23097. if (!clickInfo.hasSwiped &&
  23098. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  23099. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  23100. _this._previousStartingPointerTime = 0;
  23101. _this._doubleClickOccured = true;
  23102. clickInfo.doubleClick = true;
  23103. clickInfo.ignore = false;
  23104. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  23105. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  23106. }
  23107. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  23108. cb(clickInfo, _this._currentPickResult);
  23109. }
  23110. else {
  23111. _this._doubleClickOccured = false;
  23112. _this._previousStartingPointerTime = _this._startingPointerTime;
  23113. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  23114. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  23115. _this._previousButtonPressed = btn;
  23116. if (Scene.ExclusiveDoubleClickMode) {
  23117. if (_this._previousDelayedSimpleClickTimeout) {
  23118. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  23119. }
  23120. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  23121. cb(clickInfo, _this._previousPickResult);
  23122. }
  23123. else {
  23124. cb(clickInfo, _this._currentPickResult);
  23125. }
  23126. }
  23127. }
  23128. else {
  23129. _this._doubleClickOccured = false;
  23130. _this._previousStartingPointerTime = _this._startingPointerTime;
  23131. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  23132. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  23133. _this._previousButtonPressed = btn;
  23134. }
  23135. }
  23136. }
  23137. }
  23138. clickInfo.ignore = true;
  23139. cb(clickInfo, _this._currentPickResult);
  23140. };
  23141. this._spritePredicate = function (sprite) {
  23142. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  23143. };
  23144. this._onPointerMove = function (evt) {
  23145. _this._updatePointerPosition(evt);
  23146. // PreObservable support
  23147. if (_this.onPrePointerObservable.hasObservers()) {
  23148. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  23149. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23150. _this.onPrePointerObservable.notifyObservers(pi, type);
  23151. if (pi.skipOnPointerObservable) {
  23152. return;
  23153. }
  23154. }
  23155. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23156. return;
  23157. }
  23158. if (!_this.pointerMovePredicate) {
  23159. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  23160. }
  23161. // Meshes
  23162. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  23163. _this._processPointerMove(pickResult, evt);
  23164. };
  23165. this._onPointerDown = function (evt) {
  23166. _this._totalPointersPressed++;
  23167. _this._pickedDownMesh = null;
  23168. _this._meshPickProceed = false;
  23169. _this._updatePointerPosition(evt);
  23170. if (_this.preventDefaultOnPointerDown && canvas) {
  23171. evt.preventDefault();
  23172. canvas.focus();
  23173. }
  23174. // PreObservable support
  23175. if (_this.onPrePointerObservable.hasObservers()) {
  23176. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  23177. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23178. _this.onPrePointerObservable.notifyObservers(pi, type);
  23179. if (pi.skipOnPointerObservable) {
  23180. return;
  23181. }
  23182. }
  23183. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23184. return;
  23185. }
  23186. _this._startingPointerPosition.x = _this._pointerX;
  23187. _this._startingPointerPosition.y = _this._pointerY;
  23188. _this._startingPointerTime = new Date().getTime();
  23189. if (!_this.pointerDownPredicate) {
  23190. _this.pointerDownPredicate = function (mesh) {
  23191. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23192. };
  23193. }
  23194. // Meshes
  23195. _this._pickedDownMesh = null;
  23196. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  23197. _this._processPointerDown(pickResult, evt);
  23198. // Sprites
  23199. _this._pickedDownSprite = null;
  23200. if (_this.spriteManagers.length > 0) {
  23201. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23202. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  23203. if (pickResult.pickedSprite.actionManager) {
  23204. _this._pickedDownSprite = pickResult.pickedSprite;
  23205. switch (evt.button) {
  23206. case 0:
  23207. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23208. break;
  23209. case 1:
  23210. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23211. break;
  23212. case 2:
  23213. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23214. break;
  23215. }
  23216. if (pickResult.pickedSprite.actionManager) {
  23217. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  23218. }
  23219. }
  23220. }
  23221. }
  23222. };
  23223. this._onPointerUp = function (evt) {
  23224. if (_this._totalPointersPressed === 0) {
  23225. return; // So we need to test it the pointer down was pressed before.
  23226. }
  23227. _this._totalPointersPressed--;
  23228. _this._pickedUpMesh = null;
  23229. _this._meshPickProceed = false;
  23230. _this._updatePointerPosition(evt);
  23231. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  23232. // PreObservable support
  23233. if (_this.onPrePointerObservable.hasObservers()) {
  23234. if (!clickInfo.ignore) {
  23235. if (!clickInfo.hasSwiped) {
  23236. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  23237. var type = BABYLON.PointerEventTypes.POINTERTAP;
  23238. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23239. _this.onPrePointerObservable.notifyObservers(pi, type);
  23240. if (pi.skipOnPointerObservable) {
  23241. return;
  23242. }
  23243. }
  23244. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  23245. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  23246. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23247. _this.onPrePointerObservable.notifyObservers(pi, type);
  23248. if (pi.skipOnPointerObservable) {
  23249. return;
  23250. }
  23251. }
  23252. }
  23253. }
  23254. else {
  23255. var type = BABYLON.PointerEventTypes.POINTERUP;
  23256. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  23257. _this.onPrePointerObservable.notifyObservers(pi, type);
  23258. if (pi.skipOnPointerObservable) {
  23259. return;
  23260. }
  23261. }
  23262. }
  23263. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23264. return;
  23265. }
  23266. if (!_this.pointerUpPredicate) {
  23267. _this.pointerUpPredicate = function (mesh) {
  23268. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23269. };
  23270. }
  23271. // Meshes
  23272. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23273. _this._initActionManager(null, clickInfo);
  23274. }
  23275. if (!pickResult) {
  23276. pickResult = _this._currentPickResult;
  23277. }
  23278. _this._processPointerUp(pickResult, evt, clickInfo);
  23279. // Sprites
  23280. if (_this.spriteManagers.length > 0) {
  23281. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23282. if (spritePickResult) {
  23283. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23284. if (spritePickResult.pickedSprite.actionManager) {
  23285. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23286. if (spritePickResult.pickedSprite.actionManager) {
  23287. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23288. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23289. }
  23290. }
  23291. }
  23292. }
  23293. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23294. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23295. }
  23296. }
  23297. }
  23298. _this._previousPickResult = _this._currentPickResult;
  23299. });
  23300. };
  23301. this._onKeyDown = function (evt) {
  23302. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23303. if (_this.onPreKeyboardObservable.hasObservers()) {
  23304. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23305. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23306. if (pi.skipOnPointerObservable) {
  23307. return;
  23308. }
  23309. }
  23310. if (_this.onKeyboardObservable.hasObservers()) {
  23311. var pi = new BABYLON.KeyboardInfo(type, evt);
  23312. _this.onKeyboardObservable.notifyObservers(pi, type);
  23313. }
  23314. if (_this.actionManager) {
  23315. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23316. }
  23317. };
  23318. this._onKeyUp = function (evt) {
  23319. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23320. if (_this.onPreKeyboardObservable.hasObservers()) {
  23321. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23322. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23323. if (pi.skipOnPointerObservable) {
  23324. return;
  23325. }
  23326. }
  23327. if (_this.onKeyboardObservable.hasObservers()) {
  23328. var pi = new BABYLON.KeyboardInfo(type, evt);
  23329. _this.onKeyboardObservable.notifyObservers(pi, type);
  23330. }
  23331. if (_this.actionManager) {
  23332. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23333. }
  23334. };
  23335. var engine = this.getEngine();
  23336. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23337. if (!canvas) {
  23338. return;
  23339. }
  23340. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23341. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23342. });
  23343. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23344. if (!canvas) {
  23345. return;
  23346. }
  23347. canvas.removeEventListener("keydown", _this._onKeyDown);
  23348. canvas.removeEventListener("keyup", _this._onKeyUp);
  23349. });
  23350. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23351. var canvas = this._engine.getRenderingCanvas();
  23352. if (!canvas) {
  23353. return;
  23354. }
  23355. if (attachMove) {
  23356. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23357. // Wheel
  23358. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23359. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23360. }
  23361. if (attachDown) {
  23362. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23363. }
  23364. if (attachUp) {
  23365. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23366. }
  23367. canvas.tabIndex = 1;
  23368. };
  23369. /** Detaches all event handlers*/
  23370. Scene.prototype.detachControl = function () {
  23371. var engine = this.getEngine();
  23372. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23373. var canvas = engine.getRenderingCanvas();
  23374. if (!canvas) {
  23375. return;
  23376. }
  23377. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23378. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23379. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23380. if (this._onCanvasBlurObserver) {
  23381. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23382. }
  23383. if (this._onCanvasFocusObserver) {
  23384. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23385. }
  23386. // Wheel
  23387. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23388. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23389. // Keyboard
  23390. canvas.removeEventListener("keydown", this._onKeyDown);
  23391. canvas.removeEventListener("keyup", this._onKeyUp);
  23392. // Observables
  23393. this.onKeyboardObservable.clear();
  23394. this.onPreKeyboardObservable.clear();
  23395. this.onPointerObservable.clear();
  23396. this.onPrePointerObservable.clear();
  23397. };
  23398. /**
  23399. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23400. * Delay loaded resources are not taking in account
  23401. * @return true if all required resources are ready
  23402. */
  23403. Scene.prototype.isReady = function () {
  23404. if (this._isDisposed) {
  23405. return false;
  23406. }
  23407. if (this._pendingData.length > 0) {
  23408. return false;
  23409. }
  23410. var index;
  23411. var engine = this.getEngine();
  23412. // Geometries
  23413. for (index = 0; index < this._geometries.length; index++) {
  23414. var geometry = this._geometries[index];
  23415. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23416. return false;
  23417. }
  23418. }
  23419. // Meshes
  23420. for (index = 0; index < this.meshes.length; index++) {
  23421. var mesh = this.meshes[index];
  23422. if (!mesh.isEnabled()) {
  23423. continue;
  23424. }
  23425. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23426. continue;
  23427. }
  23428. if (!mesh.isReady(true)) {
  23429. return false;
  23430. }
  23431. // Effect layers
  23432. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23433. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23434. var layer = _a[_i];
  23435. if (!layer.hasMesh(mesh)) {
  23436. continue;
  23437. }
  23438. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23439. var subMesh = _c[_b];
  23440. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23441. return false;
  23442. }
  23443. }
  23444. }
  23445. }
  23446. // Post-processes
  23447. if (this.activeCameras && this.activeCameras.length > 0) {
  23448. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23449. var camera = _e[_d];
  23450. if (!camera.isReady(true)) {
  23451. return false;
  23452. }
  23453. }
  23454. }
  23455. else if (this.activeCamera) {
  23456. if (!this.activeCamera.isReady(true)) {
  23457. return false;
  23458. }
  23459. }
  23460. // Particles
  23461. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23462. var particleSystem = _g[_f];
  23463. if (!particleSystem.isReady()) {
  23464. return false;
  23465. }
  23466. }
  23467. return true;
  23468. };
  23469. /** Resets all cached information relative to material (including effect and visibility) */
  23470. Scene.prototype.resetCachedMaterial = function () {
  23471. this._cachedMaterial = null;
  23472. this._cachedEffect = null;
  23473. this._cachedVisibility = null;
  23474. };
  23475. /**
  23476. * Registers a function to be called before every frame render
  23477. * @param func defines the function to register
  23478. */
  23479. Scene.prototype.registerBeforeRender = function (func) {
  23480. this.onBeforeRenderObservable.add(func);
  23481. };
  23482. /**
  23483. * Unregisters a function called before every frame render
  23484. * @param func defines the function to unregister
  23485. */
  23486. Scene.prototype.unregisterBeforeRender = function (func) {
  23487. this.onBeforeRenderObservable.removeCallback(func);
  23488. };
  23489. /**
  23490. * Registers a function to be called after every frame render
  23491. * @param func defines the function to register
  23492. */
  23493. Scene.prototype.registerAfterRender = function (func) {
  23494. this.onAfterRenderObservable.add(func);
  23495. };
  23496. /**
  23497. * Unregisters a function called after every frame render
  23498. * @param func defines the function to unregister
  23499. */
  23500. Scene.prototype.unregisterAfterRender = function (func) {
  23501. this.onAfterRenderObservable.removeCallback(func);
  23502. };
  23503. Scene.prototype._executeOnceBeforeRender = function (func) {
  23504. var _this = this;
  23505. var execFunc = function () {
  23506. func();
  23507. setTimeout(function () {
  23508. _this.unregisterBeforeRender(execFunc);
  23509. });
  23510. };
  23511. this.registerBeforeRender(execFunc);
  23512. };
  23513. /**
  23514. * The provided function will run before render once and will be disposed afterwards.
  23515. * A timeout delay can be provided so that the function will be executed in N ms.
  23516. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23517. * @param func The function to be executed.
  23518. * @param timeout optional delay in ms
  23519. */
  23520. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23521. var _this = this;
  23522. if (timeout !== undefined) {
  23523. setTimeout(function () {
  23524. _this._executeOnceBeforeRender(func);
  23525. }, timeout);
  23526. }
  23527. else {
  23528. this._executeOnceBeforeRender(func);
  23529. }
  23530. };
  23531. /** @ignore */
  23532. Scene.prototype._addPendingData = function (data) {
  23533. this._pendingData.push(data);
  23534. };
  23535. /** @ignore */
  23536. Scene.prototype._removePendingData = function (data) {
  23537. var wasLoading = this.isLoading;
  23538. var index = this._pendingData.indexOf(data);
  23539. if (index !== -1) {
  23540. this._pendingData.splice(index, 1);
  23541. }
  23542. if (wasLoading && !this.isLoading) {
  23543. this.onDataLoadedObservable.notifyObservers(this);
  23544. }
  23545. };
  23546. /**
  23547. * Returns the number of items waiting to be loaded
  23548. * @returns the number of items waiting to be loaded
  23549. */
  23550. Scene.prototype.getWaitingItemsCount = function () {
  23551. return this._pendingData.length;
  23552. };
  23553. Object.defineProperty(Scene.prototype, "isLoading", {
  23554. /**
  23555. * Returns a boolean indicating if the scene is still loading data
  23556. */
  23557. get: function () {
  23558. return this._pendingData.length > 0;
  23559. },
  23560. enumerable: true,
  23561. configurable: true
  23562. });
  23563. /**
  23564. * Registers a function to be executed when the scene is ready
  23565. * @param {Function} func - the function to be executed
  23566. */
  23567. Scene.prototype.executeWhenReady = function (func) {
  23568. var _this = this;
  23569. this.onReadyObservable.add(func);
  23570. if (this._executeWhenReadyTimeoutId !== -1) {
  23571. return;
  23572. }
  23573. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23574. _this._checkIsReady();
  23575. }, 150);
  23576. };
  23577. /**
  23578. * Returns a promise that resolves when the scene is ready
  23579. * @returns A promise that resolves when the scene is ready
  23580. */
  23581. Scene.prototype.whenReadyAsync = function () {
  23582. var _this = this;
  23583. return new Promise(function (resolve) {
  23584. _this.executeWhenReady(function () {
  23585. resolve();
  23586. });
  23587. });
  23588. };
  23589. /** @ignore */
  23590. Scene.prototype._checkIsReady = function () {
  23591. var _this = this;
  23592. if (this.isReady()) {
  23593. this.onReadyObservable.notifyObservers(this);
  23594. this.onReadyObservable.clear();
  23595. this._executeWhenReadyTimeoutId = -1;
  23596. return;
  23597. }
  23598. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23599. _this._checkIsReady();
  23600. }, 150);
  23601. };
  23602. // Animations
  23603. /**
  23604. * Will start the animation sequence of a given target
  23605. * @param target defines the target
  23606. * @param from defines from which frame should animation start
  23607. * @param to defines until which frame should animation run.
  23608. * @param weight defines the weight to apply to the animation (1.0 by default)
  23609. * @param loop defines if the animation loops
  23610. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23611. * @param onAnimationEnd defines the function to be executed when the animation ends
  23612. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23613. * @returns the animatable object created for this animation
  23614. */
  23615. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23616. if (weight === void 0) { weight = 1.0; }
  23617. if (speedRatio === void 0) { speedRatio = 1.0; }
  23618. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23619. returnedAnimatable.weight = weight;
  23620. return returnedAnimatable;
  23621. };
  23622. /**
  23623. * Will start the animation sequence of a given target
  23624. * @param target defines the target
  23625. * @param from defines from which frame should animation start
  23626. * @param to defines until which frame should animation run.
  23627. * @param loop defines if the animation loops
  23628. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23629. * @param onAnimationEnd defines the function to be executed when the animation ends
  23630. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23631. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23632. * @returns the animatable object created for this animation
  23633. */
  23634. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23635. if (speedRatio === void 0) { speedRatio = 1.0; }
  23636. if (stopCurrent === void 0) { stopCurrent = true; }
  23637. if (from > to && speedRatio > 0) {
  23638. speedRatio *= -1;
  23639. }
  23640. if (stopCurrent) {
  23641. this.stopAnimation(target);
  23642. }
  23643. if (!animatable) {
  23644. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23645. }
  23646. // Local animations
  23647. if (target.animations) {
  23648. animatable.appendAnimations(target, target.animations);
  23649. }
  23650. // Children animations
  23651. if (target.getAnimatables) {
  23652. var animatables = target.getAnimatables();
  23653. for (var index = 0; index < animatables.length; index++) {
  23654. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23655. }
  23656. }
  23657. animatable.reset();
  23658. return animatable;
  23659. };
  23660. /**
  23661. * Begin a new animation on a given node
  23662. * @param target defines the target where the animation will take place
  23663. * @param animations defines the list of animations to start
  23664. * @param from defines the initial value
  23665. * @param to defines the final value
  23666. * @param loop defines if you want animation to loop (off by default)
  23667. * @param speedRatio defines the speed ratio to apply to all animations
  23668. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23669. * @returns the list of created animatables
  23670. */
  23671. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23672. if (speedRatio === undefined) {
  23673. speedRatio = 1.0;
  23674. }
  23675. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23676. return animatable;
  23677. };
  23678. /**
  23679. * Begin a new animation on a given node and its hierarchy
  23680. * @param target defines the root node where the animation will take place
  23681. * @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.
  23682. * @param animations defines the list of animations to start
  23683. * @param from defines the initial value
  23684. * @param to defines the final value
  23685. * @param loop defines if you want animation to loop (off by default)
  23686. * @param speedRatio defines the speed ratio to apply to all animations
  23687. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23688. * @returns the list of animatables created for all nodes
  23689. */
  23690. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23691. var children = target.getDescendants(directDescendantsOnly);
  23692. var result = [];
  23693. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23694. var child = children_1[_i];
  23695. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23696. }
  23697. return result;
  23698. };
  23699. /**
  23700. * Gets the animatable associated with a specific target
  23701. * @param target defines the target of the animatable
  23702. * @returns the required animatable if found
  23703. */
  23704. Scene.prototype.getAnimatableByTarget = function (target) {
  23705. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23706. if (this._activeAnimatables[index].target === target) {
  23707. return this._activeAnimatables[index];
  23708. }
  23709. }
  23710. return null;
  23711. };
  23712. /**
  23713. * Gets all animatables associated with a given target
  23714. * @param target defines the target to look animatables for
  23715. * @returns an array of Animatables
  23716. */
  23717. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23718. var result = [];
  23719. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23720. if (this._activeAnimatables[index].target === target) {
  23721. result.push(this._activeAnimatables[index]);
  23722. }
  23723. }
  23724. return result;
  23725. };
  23726. Object.defineProperty(Scene.prototype, "animatables", {
  23727. /**
  23728. * Gets all animatable attached to the scene
  23729. */
  23730. get: function () {
  23731. return this._activeAnimatables;
  23732. },
  23733. enumerable: true,
  23734. configurable: true
  23735. });
  23736. /**
  23737. * Will stop the animation of the given target
  23738. * @param target - the target
  23739. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23740. */
  23741. Scene.prototype.stopAnimation = function (target, animationName) {
  23742. var animatables = this.getAllAnimatablesByTarget(target);
  23743. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23744. var animatable = animatables_1[_i];
  23745. animatable.stop(animationName);
  23746. }
  23747. };
  23748. /**
  23749. * Stops and removes all animations that have been applied to the scene
  23750. */
  23751. Scene.prototype.stopAllAnimations = function () {
  23752. if (this._activeAnimatables) {
  23753. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23754. this._activeAnimatables[i].stop();
  23755. }
  23756. this._activeAnimatables = [];
  23757. }
  23758. };
  23759. Scene.prototype._animate = function () {
  23760. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23761. return;
  23762. }
  23763. // Getting time
  23764. var now = BABYLON.Tools.Now;
  23765. if (!this._animationTimeLast) {
  23766. if (this._pendingData.length > 0) {
  23767. return;
  23768. }
  23769. this._animationTimeLast = now;
  23770. }
  23771. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23772. this._animationTime += deltaTime;
  23773. this._animationTimeLast = now;
  23774. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23775. this._activeAnimatables[index]._animate(this._animationTime);
  23776. }
  23777. // Late animation bindings
  23778. this._processLateAnimationBindings();
  23779. };
  23780. /** @ignore */
  23781. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23782. var target = runtimeAnimation.target;
  23783. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23784. if (!target._lateAnimationHolders) {
  23785. target._lateAnimationHolders = {};
  23786. }
  23787. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23788. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23789. totalWeight: 0,
  23790. animations: []
  23791. };
  23792. }
  23793. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23794. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23795. };
  23796. Scene.prototype._processLateAnimationBindings = function () {
  23797. if (!this._registeredForLateAnimationBindings.length) {
  23798. return;
  23799. }
  23800. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23801. var target = this._registeredForLateAnimationBindings.data[index];
  23802. for (var path in target._lateAnimationHolders) {
  23803. var holder = target._lateAnimationHolders[path];
  23804. // Sanity check
  23805. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23806. continue;
  23807. }
  23808. var normalizer = 1.0;
  23809. var finalValue = void 0;
  23810. if (holder.totalWeight < 1.0) {
  23811. // We need to mix the original value in
  23812. var originalValue = holder.animations[0].originalValue;
  23813. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23814. }
  23815. else {
  23816. // We need to normalize the weights
  23817. normalizer = holder.totalWeight;
  23818. }
  23819. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23820. var runtimeAnimation = holder.animations[animIndex];
  23821. if (finalValue) {
  23822. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23823. }
  23824. else {
  23825. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23826. }
  23827. }
  23828. runtimeAnimation.target[path] = finalValue;
  23829. }
  23830. target._lateAnimationHolders = {};
  23831. }
  23832. this._registeredForLateAnimationBindings.reset();
  23833. };
  23834. // Matrix
  23835. /** @ignore */
  23836. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23837. this._useAlternateCameraConfiguration = active;
  23838. };
  23839. /**
  23840. * Gets the current view matrix
  23841. * @returns a Matrix
  23842. */
  23843. Scene.prototype.getViewMatrix = function () {
  23844. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23845. };
  23846. /**
  23847. * Gets the current projection matrix
  23848. * @returns a Matrix
  23849. */
  23850. Scene.prototype.getProjectionMatrix = function () {
  23851. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23852. };
  23853. /**
  23854. * Gets the current transform matrix
  23855. * @returns a Matrix made of View * Projection
  23856. */
  23857. Scene.prototype.getTransformMatrix = function () {
  23858. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23859. };
  23860. /**
  23861. * Sets the current transform matrix
  23862. * @param view defines the View matrix to use
  23863. * @param projection defines the Projection matrix to use
  23864. */
  23865. Scene.prototype.setTransformMatrix = function (view, projection) {
  23866. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23867. return;
  23868. }
  23869. this._viewUpdateFlag = view.updateFlag;
  23870. this._projectionUpdateFlag = projection.updateFlag;
  23871. this._viewMatrix = view;
  23872. this._projectionMatrix = projection;
  23873. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23874. // Update frustum
  23875. if (!this._frustumPlanes) {
  23876. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23877. }
  23878. else {
  23879. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23880. }
  23881. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23882. var otherCamera = this.activeCamera._alternateCamera;
  23883. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23884. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23885. }
  23886. if (this._sceneUbo.useUbo) {
  23887. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23888. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23889. this._sceneUbo.update();
  23890. }
  23891. };
  23892. /** @ignore */
  23893. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23894. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23895. return;
  23896. }
  23897. this._alternateViewUpdateFlag = view.updateFlag;
  23898. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23899. this._alternateViewMatrix = view;
  23900. this._alternateProjectionMatrix = projection;
  23901. if (!this._alternateTransformMatrix) {
  23902. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23903. }
  23904. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23905. if (!this._alternateSceneUbo) {
  23906. this._createAlternateUbo();
  23907. }
  23908. if (this._alternateSceneUbo.useUbo) {
  23909. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23910. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23911. this._alternateSceneUbo.update();
  23912. }
  23913. };
  23914. /**
  23915. * Gets the uniform buffer used to store scene data
  23916. * @returns a UniformBuffer
  23917. */
  23918. Scene.prototype.getSceneUniformBuffer = function () {
  23919. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23920. };
  23921. /**
  23922. * Gets an unique (relatively to the current scene) Id
  23923. * @returns an unique number for the scene
  23924. */
  23925. Scene.prototype.getUniqueId = function () {
  23926. var result = Scene._uniqueIdCounter;
  23927. Scene._uniqueIdCounter++;
  23928. return result;
  23929. };
  23930. /**
  23931. * Add a mesh to the list of scene's meshes
  23932. * @param newMesh defines the mesh to add
  23933. */
  23934. Scene.prototype.addMesh = function (newMesh) {
  23935. this.meshes.push(newMesh);
  23936. //notify the collision coordinator
  23937. if (this.collisionCoordinator) {
  23938. this.collisionCoordinator.onMeshAdded(newMesh);
  23939. }
  23940. newMesh._resyncLightSources();
  23941. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23942. };
  23943. /**
  23944. * Remove a mesh for the list of scene's meshes
  23945. * @param toRemove defines the mesh to remove
  23946. * @returns the index where the mesh was in the mesh list
  23947. */
  23948. Scene.prototype.removeMesh = function (toRemove) {
  23949. var index = this.meshes.indexOf(toRemove);
  23950. if (index !== -1) {
  23951. // Remove from the scene if mesh found
  23952. this.meshes.splice(index, 1);
  23953. }
  23954. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23955. return index;
  23956. };
  23957. /**
  23958. * Add a transform node to the list of scene's transform nodes
  23959. * @param newTransformNode defines the transform node to add
  23960. */
  23961. Scene.prototype.addTransformNode = function (newTransformNode) {
  23962. this.transformNodes.push(newTransformNode);
  23963. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23964. };
  23965. /**
  23966. * Remove a transform node for the list of scene's transform nodes
  23967. * @param toRemove defines the transform node to remove
  23968. * @returns the index where the transform node was in the transform node list
  23969. */
  23970. Scene.prototype.removeTransformNode = function (toRemove) {
  23971. var index = this.transformNodes.indexOf(toRemove);
  23972. if (index !== -1) {
  23973. // Remove from the scene if found
  23974. this.transformNodes.splice(index, 1);
  23975. }
  23976. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23977. return index;
  23978. };
  23979. /**
  23980. * Remove a skeleton for the list of scene's skeletons
  23981. * @param toRemove defines the skeleton to remove
  23982. * @returns the index where the skeleton was in the skeleton list
  23983. */
  23984. Scene.prototype.removeSkeleton = function (toRemove) {
  23985. var index = this.skeletons.indexOf(toRemove);
  23986. if (index !== -1) {
  23987. // Remove from the scene if found
  23988. this.skeletons.splice(index, 1);
  23989. }
  23990. return index;
  23991. };
  23992. /**
  23993. * Remove a morph target for the list of scene's morph targets
  23994. * @param toRemove defines the morph target to remove
  23995. * @returns the index where the morph target was in the morph target list
  23996. */
  23997. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23998. var index = this.morphTargetManagers.indexOf(toRemove);
  23999. if (index !== -1) {
  24000. // Remove from the scene if found
  24001. this.morphTargetManagers.splice(index, 1);
  24002. }
  24003. return index;
  24004. };
  24005. /**
  24006. * Remove a light for the list of scene's lights
  24007. * @param toRemove defines the light to remove
  24008. * @returns the index where the light was in the light list
  24009. */
  24010. Scene.prototype.removeLight = function (toRemove) {
  24011. var index = this.lights.indexOf(toRemove);
  24012. if (index !== -1) {
  24013. // Remove from meshes
  24014. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  24015. var mesh = _a[_i];
  24016. mesh._removeLightSource(toRemove);
  24017. }
  24018. // Remove from the scene if mesh found
  24019. this.lights.splice(index, 1);
  24020. this.sortLightsByPriority();
  24021. }
  24022. this.onLightRemovedObservable.notifyObservers(toRemove);
  24023. return index;
  24024. };
  24025. /**
  24026. * Remove a camera for the list of scene's cameras
  24027. * @param toRemove defines the camera to remove
  24028. * @returns the index where the camera was in the camera list
  24029. */
  24030. Scene.prototype.removeCamera = function (toRemove) {
  24031. var index = this.cameras.indexOf(toRemove);
  24032. if (index !== -1) {
  24033. // Remove from the scene if mesh found
  24034. this.cameras.splice(index, 1);
  24035. }
  24036. // Remove from activeCameras
  24037. var index2 = this.activeCameras.indexOf(toRemove);
  24038. if (index2 !== -1) {
  24039. // Remove from the scene if mesh found
  24040. this.activeCameras.splice(index2, 1);
  24041. }
  24042. // Reset the activeCamera
  24043. if (this.activeCamera === toRemove) {
  24044. if (this.cameras.length > 0) {
  24045. this.activeCamera = this.cameras[0];
  24046. }
  24047. else {
  24048. this.activeCamera = null;
  24049. }
  24050. }
  24051. this.onCameraRemovedObservable.notifyObservers(toRemove);
  24052. return index;
  24053. };
  24054. /**
  24055. * Remove a particle system for the list of scene's particle systems
  24056. * @param toRemove defines the particle system to remove
  24057. * @returns the index where the particle system was in the particle system list
  24058. */
  24059. Scene.prototype.removeParticleSystem = function (toRemove) {
  24060. var index = this.particleSystems.indexOf(toRemove);
  24061. if (index !== -1) {
  24062. this.particleSystems.splice(index, 1);
  24063. }
  24064. return index;
  24065. };
  24066. /**
  24067. * Remove a animation for the list of scene's animations
  24068. * @param toRemove defines the animation to remove
  24069. * @returns the index where the animation was in the animation list
  24070. */
  24071. Scene.prototype.removeAnimation = function (toRemove) {
  24072. var index = this.animations.indexOf(toRemove);
  24073. if (index !== -1) {
  24074. this.animations.splice(index, 1);
  24075. }
  24076. return index;
  24077. };
  24078. /**
  24079. * Removes the given animation group from this scene.
  24080. * @param toRemove The animation group to remove
  24081. * @returns The index of the removed animation group
  24082. */
  24083. Scene.prototype.removeAnimationGroup = function (toRemove) {
  24084. var index = this.animationGroups.indexOf(toRemove);
  24085. if (index !== -1) {
  24086. this.animationGroups.splice(index, 1);
  24087. }
  24088. return index;
  24089. };
  24090. /**
  24091. * Removes the given multi-material from this scene.
  24092. * @param toRemove The multi-material to remove
  24093. * @returns The index of the removed multi-material
  24094. */
  24095. Scene.prototype.removeMultiMaterial = function (toRemove) {
  24096. var index = this.multiMaterials.indexOf(toRemove);
  24097. if (index !== -1) {
  24098. this.multiMaterials.splice(index, 1);
  24099. }
  24100. return index;
  24101. };
  24102. /**
  24103. * Removes the given material from this scene.
  24104. * @param toRemove The material to remove
  24105. * @returns The index of the removed material
  24106. */
  24107. Scene.prototype.removeMaterial = function (toRemove) {
  24108. var index = this.materials.indexOf(toRemove);
  24109. if (index !== -1) {
  24110. this.materials.splice(index, 1);
  24111. }
  24112. return index;
  24113. };
  24114. /**
  24115. * Removes the given lens flare system from this scene.
  24116. * @param toRemove The lens flare system to remove
  24117. * @returns The index of the removed lens flare system
  24118. */
  24119. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  24120. var index = this.lensFlareSystems.indexOf(toRemove);
  24121. if (index !== -1) {
  24122. this.lensFlareSystems.splice(index, 1);
  24123. }
  24124. return index;
  24125. };
  24126. /**
  24127. * Removes the given action manager from this scene.
  24128. * @param toRemove The action manager to remove
  24129. * @returns The index of the removed action manager
  24130. */
  24131. Scene.prototype.removeActionManager = function (toRemove) {
  24132. var index = this._actionManagers.indexOf(toRemove);
  24133. if (index !== -1) {
  24134. this._actionManagers.splice(index, 1);
  24135. }
  24136. return index;
  24137. };
  24138. /**
  24139. * Removes the given texture from this scene.
  24140. * @param toRemove The texture to remove
  24141. * @returns The index of the removed texture
  24142. */
  24143. Scene.prototype.removeTexture = function (toRemove) {
  24144. var index = this.textures.indexOf(toRemove);
  24145. if (index !== -1) {
  24146. this.textures.splice(index, 1);
  24147. }
  24148. return index;
  24149. };
  24150. /**
  24151. * Adds the given light to this scene
  24152. * @param newLight The light to add
  24153. */
  24154. Scene.prototype.addLight = function (newLight) {
  24155. this.lights.push(newLight);
  24156. this.sortLightsByPriority();
  24157. // Add light to all meshes (To support if the light is removed and then readded)
  24158. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  24159. var mesh = _a[_i];
  24160. if (mesh._lightSources.indexOf(newLight) === -1) {
  24161. mesh._lightSources.push(newLight);
  24162. mesh._resyncLightSources();
  24163. }
  24164. }
  24165. this.onNewLightAddedObservable.notifyObservers(newLight);
  24166. };
  24167. /**
  24168. * Sorts the list list based on light priorities
  24169. */
  24170. Scene.prototype.sortLightsByPriority = function () {
  24171. if (this.requireLightSorting) {
  24172. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  24173. }
  24174. };
  24175. /**
  24176. * Adds the given camera to this scene
  24177. * @param newCamera The camera to add
  24178. */
  24179. Scene.prototype.addCamera = function (newCamera) {
  24180. this.cameras.push(newCamera);
  24181. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  24182. };
  24183. /**
  24184. * Adds the given skeleton to this scene
  24185. * @param newSkeleton The skeleton to add
  24186. */
  24187. Scene.prototype.addSkeleton = function (newSkeleton) {
  24188. this.skeletons.push(newSkeleton);
  24189. };
  24190. /**
  24191. * Adds the given particle system to this scene
  24192. * @param newParticleSystem The particle system to add
  24193. */
  24194. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  24195. this.particleSystems.push(newParticleSystem);
  24196. };
  24197. /**
  24198. * Adds the given animation to this scene
  24199. * @param newAnimation The animation to add
  24200. */
  24201. Scene.prototype.addAnimation = function (newAnimation) {
  24202. this.animations.push(newAnimation);
  24203. };
  24204. /**
  24205. * Adds the given animation group to this scene.
  24206. * @param newAnimationGroup The animation group to add
  24207. */
  24208. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  24209. this.animationGroups.push(newAnimationGroup);
  24210. };
  24211. /**
  24212. * Adds the given multi-material to this scene
  24213. * @param newMultiMaterial The multi-material to add
  24214. */
  24215. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  24216. this.multiMaterials.push(newMultiMaterial);
  24217. };
  24218. /**
  24219. * Adds the given material to this scene
  24220. * @param newMaterial The material to add
  24221. */
  24222. Scene.prototype.addMaterial = function (newMaterial) {
  24223. this.materials.push(newMaterial);
  24224. };
  24225. /**
  24226. * Adds the given morph target to this scene
  24227. * @param newMorphTargetManager The morph target to add
  24228. */
  24229. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  24230. this.morphTargetManagers.push(newMorphTargetManager);
  24231. };
  24232. /**
  24233. * Adds the given geometry to this scene
  24234. * @param newGeometry The geometry to add
  24235. */
  24236. Scene.prototype.addGeometry = function (newGeometry) {
  24237. this._geometries.push(newGeometry);
  24238. };
  24239. /**
  24240. * Adds the given lens flare system to this scene
  24241. * @param newLensFlareSystem The lens flare system to add
  24242. */
  24243. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  24244. this.lensFlareSystems.push(newLensFlareSystem);
  24245. };
  24246. /**
  24247. * Adds the given action manager to this scene
  24248. * @param newActionManager The action manager to add
  24249. */
  24250. Scene.prototype.addActionManager = function (newActionManager) {
  24251. this._actionManagers.push(newActionManager);
  24252. };
  24253. /**
  24254. * Adds the given texture to this scene.
  24255. * @param newTexture The texture to add
  24256. */
  24257. Scene.prototype.addTexture = function (newTexture) {
  24258. this.textures.push(newTexture);
  24259. };
  24260. /**
  24261. * Switch active camera
  24262. * @param newCamera defines the new active camera
  24263. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  24264. */
  24265. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  24266. if (attachControl === void 0) { attachControl = true; }
  24267. var canvas = this._engine.getRenderingCanvas();
  24268. if (!canvas) {
  24269. return;
  24270. }
  24271. if (this.activeCamera) {
  24272. this.activeCamera.detachControl(canvas);
  24273. }
  24274. this.activeCamera = newCamera;
  24275. if (attachControl) {
  24276. newCamera.attachControl(canvas);
  24277. }
  24278. };
  24279. /**
  24280. * sets the active camera of the scene using its ID
  24281. * @param id defines the camera's ID
  24282. * @return the new active camera or null if none found.
  24283. */
  24284. Scene.prototype.setActiveCameraByID = function (id) {
  24285. var camera = this.getCameraByID(id);
  24286. if (camera) {
  24287. this.activeCamera = camera;
  24288. return camera;
  24289. }
  24290. return null;
  24291. };
  24292. /**
  24293. * sets the active camera of the scene using its name
  24294. * @param name defines the camera's name
  24295. * @returns the new active camera or null if none found.
  24296. */
  24297. Scene.prototype.setActiveCameraByName = function (name) {
  24298. var camera = this.getCameraByName(name);
  24299. if (camera) {
  24300. this.activeCamera = camera;
  24301. return camera;
  24302. }
  24303. return null;
  24304. };
  24305. /**
  24306. * get an animation group using its name
  24307. * @param name defines the material's name
  24308. * @return the animation group or null if none found.
  24309. */
  24310. Scene.prototype.getAnimationGroupByName = function (name) {
  24311. for (var index = 0; index < this.animationGroups.length; index++) {
  24312. if (this.animationGroups[index].name === name) {
  24313. return this.animationGroups[index];
  24314. }
  24315. }
  24316. return null;
  24317. };
  24318. /**
  24319. * get a material using its id
  24320. * @param id defines the material's ID
  24321. * @return the material or null if none found.
  24322. */
  24323. Scene.prototype.getMaterialByID = function (id) {
  24324. for (var index = 0; index < this.materials.length; index++) {
  24325. if (this.materials[index].id === id) {
  24326. return this.materials[index];
  24327. }
  24328. }
  24329. return null;
  24330. };
  24331. /**
  24332. * Gets a material using its name
  24333. * @param name defines the material's name
  24334. * @return the material or null if none found.
  24335. */
  24336. Scene.prototype.getMaterialByName = function (name) {
  24337. for (var index = 0; index < this.materials.length; index++) {
  24338. if (this.materials[index].name === name) {
  24339. return this.materials[index];
  24340. }
  24341. }
  24342. return null;
  24343. };
  24344. /**
  24345. * Gets a lens flare system using its name
  24346. * @param name defines the name to look for
  24347. * @returns the lens flare system or null if not found
  24348. */
  24349. Scene.prototype.getLensFlareSystemByName = function (name) {
  24350. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  24351. if (this.lensFlareSystems[index].name === name) {
  24352. return this.lensFlareSystems[index];
  24353. }
  24354. }
  24355. return null;
  24356. };
  24357. /**
  24358. * Gets a lens flare system using its id
  24359. * @param id defines the id to look for
  24360. * @returns the lens flare system or null if not found
  24361. */
  24362. Scene.prototype.getLensFlareSystemByID = function (id) {
  24363. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  24364. if (this.lensFlareSystems[index].id === id) {
  24365. return this.lensFlareSystems[index];
  24366. }
  24367. }
  24368. return null;
  24369. };
  24370. /**
  24371. * Gets a camera using its id
  24372. * @param id defines the id to look for
  24373. * @returns the camera or null if not found
  24374. */
  24375. Scene.prototype.getCameraByID = function (id) {
  24376. for (var index = 0; index < this.cameras.length; index++) {
  24377. if (this.cameras[index].id === id) {
  24378. return this.cameras[index];
  24379. }
  24380. }
  24381. return null;
  24382. };
  24383. /**
  24384. * Gets a camera using its unique id
  24385. * @param uniqueId defines the unique id to look for
  24386. * @returns the camera or null if not found
  24387. */
  24388. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  24389. for (var index = 0; index < this.cameras.length; index++) {
  24390. if (this.cameras[index].uniqueId === uniqueId) {
  24391. return this.cameras[index];
  24392. }
  24393. }
  24394. return null;
  24395. };
  24396. /**
  24397. * Gets a camera using its name
  24398. * @param name defines the camera's name
  24399. * @return the camera or null if none found.
  24400. */
  24401. Scene.prototype.getCameraByName = function (name) {
  24402. for (var index = 0; index < this.cameras.length; index++) {
  24403. if (this.cameras[index].name === name) {
  24404. return this.cameras[index];
  24405. }
  24406. }
  24407. return null;
  24408. };
  24409. /**
  24410. * Gets a bone using its id
  24411. * @param id defines the bone's id
  24412. * @return the bone or null if not found
  24413. */
  24414. Scene.prototype.getBoneByID = function (id) {
  24415. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24416. var skeleton = this.skeletons[skeletonIndex];
  24417. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24418. if (skeleton.bones[boneIndex].id === id) {
  24419. return skeleton.bones[boneIndex];
  24420. }
  24421. }
  24422. }
  24423. return null;
  24424. };
  24425. /**
  24426. * Gets a bone using its id
  24427. * @param name defines the bone's name
  24428. * @return the bone or null if not found
  24429. */
  24430. Scene.prototype.getBoneByName = function (name) {
  24431. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  24432. var skeleton = this.skeletons[skeletonIndex];
  24433. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  24434. if (skeleton.bones[boneIndex].name === name) {
  24435. return skeleton.bones[boneIndex];
  24436. }
  24437. }
  24438. }
  24439. return null;
  24440. };
  24441. /**
  24442. * Gets a light node using its name
  24443. * @param name defines the the light's name
  24444. * @return the light or null if none found.
  24445. */
  24446. Scene.prototype.getLightByName = function (name) {
  24447. for (var index = 0; index < this.lights.length; index++) {
  24448. if (this.lights[index].name === name) {
  24449. return this.lights[index];
  24450. }
  24451. }
  24452. return null;
  24453. };
  24454. /**
  24455. * Gets a light node using its id
  24456. * @param id defines the light's id
  24457. * @return the light or null if none found.
  24458. */
  24459. Scene.prototype.getLightByID = function (id) {
  24460. for (var index = 0; index < this.lights.length; index++) {
  24461. if (this.lights[index].id === id) {
  24462. return this.lights[index];
  24463. }
  24464. }
  24465. return null;
  24466. };
  24467. /**
  24468. * Gets a light node using its scene-generated unique ID
  24469. * @param uniqueId defines the light's unique id
  24470. * @return the light or null if none found.
  24471. */
  24472. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  24473. for (var index = 0; index < this.lights.length; index++) {
  24474. if (this.lights[index].uniqueId === uniqueId) {
  24475. return this.lights[index];
  24476. }
  24477. }
  24478. return null;
  24479. };
  24480. /**
  24481. * Gets a particle system by id
  24482. * @param id defines the particle system id
  24483. * @return the corresponding system or null if none found
  24484. */
  24485. Scene.prototype.getParticleSystemByID = function (id) {
  24486. for (var index = 0; index < this.particleSystems.length; index++) {
  24487. if (this.particleSystems[index].id === id) {
  24488. return this.particleSystems[index];
  24489. }
  24490. }
  24491. return null;
  24492. };
  24493. /**
  24494. * Gets a geometry using its ID
  24495. * @param id defines the geometry's id
  24496. * @return the geometry or null if none found.
  24497. */
  24498. Scene.prototype.getGeometryByID = function (id) {
  24499. for (var index = 0; index < this._geometries.length; index++) {
  24500. if (this._geometries[index].id === id) {
  24501. return this._geometries[index];
  24502. }
  24503. }
  24504. return null;
  24505. };
  24506. /**
  24507. * Add a new geometry to this scene
  24508. * @param geometry defines the geometry to be added to the scene.
  24509. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  24510. * @return a boolean defining if the geometry was added or not
  24511. */
  24512. Scene.prototype.pushGeometry = function (geometry, force) {
  24513. if (!force && this.getGeometryByID(geometry.id)) {
  24514. return false;
  24515. }
  24516. this._geometries.push(geometry);
  24517. //notify the collision coordinator
  24518. if (this.collisionCoordinator) {
  24519. this.collisionCoordinator.onGeometryAdded(geometry);
  24520. }
  24521. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24522. return true;
  24523. };
  24524. /**
  24525. * Removes an existing geometry
  24526. * @param geometry defines the geometry to be removed from the scene
  24527. * @return a boolean defining if the geometry was removed or not
  24528. */
  24529. Scene.prototype.removeGeometry = function (geometry) {
  24530. var index = this._geometries.indexOf(geometry);
  24531. if (index > -1) {
  24532. this._geometries.splice(index, 1);
  24533. //notify the collision coordinator
  24534. if (this.collisionCoordinator) {
  24535. this.collisionCoordinator.onGeometryDeleted(geometry);
  24536. }
  24537. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24538. return true;
  24539. }
  24540. return false;
  24541. };
  24542. /**
  24543. * Gets the list of geometries attached to the scene
  24544. * @returns an array of Geometry
  24545. */
  24546. Scene.prototype.getGeometries = function () {
  24547. return this._geometries;
  24548. };
  24549. /**
  24550. * Gets the first added mesh found of a given ID
  24551. * @param id defines the id to search for
  24552. * @return the mesh found or null if not found at all
  24553. */
  24554. Scene.prototype.getMeshByID = function (id) {
  24555. for (var index = 0; index < this.meshes.length; index++) {
  24556. if (this.meshes[index].id === id) {
  24557. return this.meshes[index];
  24558. }
  24559. }
  24560. return null;
  24561. };
  24562. /**
  24563. * Gets a list of meshes using their id
  24564. * @param id defines the id to search for
  24565. * @returns a list of meshes
  24566. */
  24567. Scene.prototype.getMeshesByID = function (id) {
  24568. return this.meshes.filter(function (m) {
  24569. return m.id === id;
  24570. });
  24571. };
  24572. /**
  24573. * Gets the first added transform node found of a given ID
  24574. * @param id defines the id to search for
  24575. * @return the found transform node or null if not found at all.
  24576. */
  24577. Scene.prototype.getTransformNodeByID = function (id) {
  24578. for (var index = 0; index < this.transformNodes.length; index++) {
  24579. if (this.transformNodes[index].id === id) {
  24580. return this.transformNodes[index];
  24581. }
  24582. }
  24583. return null;
  24584. };
  24585. /**
  24586. * Gets a list of transform nodes using their id
  24587. * @param id defines the id to search for
  24588. * @returns a list of transform nodes
  24589. */
  24590. Scene.prototype.getTransformNodesByID = function (id) {
  24591. return this.transformNodes.filter(function (m) {
  24592. return m.id === id;
  24593. });
  24594. };
  24595. /**
  24596. * Gets a mesh with its auto-generated unique id
  24597. * @param uniqueId defines the unique id to search for
  24598. * @return the found mesh or null if not found at all.
  24599. */
  24600. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24601. for (var index = 0; index < this.meshes.length; index++) {
  24602. if (this.meshes[index].uniqueId === uniqueId) {
  24603. return this.meshes[index];
  24604. }
  24605. }
  24606. return null;
  24607. };
  24608. /**
  24609. * Gets a the last added mesh using a given id
  24610. * @param id defines the id to search for
  24611. * @return the found mesh or null if not found at all.
  24612. */
  24613. Scene.prototype.getLastMeshByID = function (id) {
  24614. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24615. if (this.meshes[index].id === id) {
  24616. return this.meshes[index];
  24617. }
  24618. }
  24619. return null;
  24620. };
  24621. /**
  24622. * Gets a the last added node (Mesh, Camera, Light) using a given id
  24623. * @param id defines the id to search for
  24624. * @return the found node or null if not found at all
  24625. */
  24626. Scene.prototype.getLastEntryByID = function (id) {
  24627. var index;
  24628. for (index = this.meshes.length - 1; index >= 0; index--) {
  24629. if (this.meshes[index].id === id) {
  24630. return this.meshes[index];
  24631. }
  24632. }
  24633. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24634. if (this.transformNodes[index].id === id) {
  24635. return this.transformNodes[index];
  24636. }
  24637. }
  24638. for (index = this.cameras.length - 1; index >= 0; index--) {
  24639. if (this.cameras[index].id === id) {
  24640. return this.cameras[index];
  24641. }
  24642. }
  24643. for (index = this.lights.length - 1; index >= 0; index--) {
  24644. if (this.lights[index].id === id) {
  24645. return this.lights[index];
  24646. }
  24647. }
  24648. return null;
  24649. };
  24650. /**
  24651. * Gets a node (Mesh, Camera, Light) using a given id
  24652. * @param id defines the id to search for
  24653. * @return the found node or null if not found at all
  24654. */
  24655. Scene.prototype.getNodeByID = function (id) {
  24656. var mesh = this.getMeshByID(id);
  24657. if (mesh) {
  24658. return mesh;
  24659. }
  24660. var light = this.getLightByID(id);
  24661. if (light) {
  24662. return light;
  24663. }
  24664. var camera = this.getCameraByID(id);
  24665. if (camera) {
  24666. return camera;
  24667. }
  24668. var bone = this.getBoneByID(id);
  24669. return bone;
  24670. };
  24671. /**
  24672. * Gets a node (Mesh, Camera, Light) using a given name
  24673. * @param name defines the name to search for
  24674. * @return the found node or null if not found at all.
  24675. */
  24676. Scene.prototype.getNodeByName = function (name) {
  24677. var mesh = this.getMeshByName(name);
  24678. if (mesh) {
  24679. return mesh;
  24680. }
  24681. var light = this.getLightByName(name);
  24682. if (light) {
  24683. return light;
  24684. }
  24685. var camera = this.getCameraByName(name);
  24686. if (camera) {
  24687. return camera;
  24688. }
  24689. var bone = this.getBoneByName(name);
  24690. return bone;
  24691. };
  24692. /**
  24693. * Gets a mesh using a given name
  24694. * @param name defines the name to search for
  24695. * @return the found mesh or null if not found at all.
  24696. */
  24697. Scene.prototype.getMeshByName = function (name) {
  24698. for (var index = 0; index < this.meshes.length; index++) {
  24699. if (this.meshes[index].name === name) {
  24700. return this.meshes[index];
  24701. }
  24702. }
  24703. return null;
  24704. };
  24705. /**
  24706. * Gets a transform node using a given name
  24707. * @param name defines the name to search for
  24708. * @return the found transform node or null if not found at all.
  24709. */
  24710. Scene.prototype.getTransformNodeByName = function (name) {
  24711. for (var index = 0; index < this.transformNodes.length; index++) {
  24712. if (this.transformNodes[index].name === name) {
  24713. return this.transformNodes[index];
  24714. }
  24715. }
  24716. return null;
  24717. };
  24718. /**
  24719. * Gets a sound using a given name
  24720. * @param name defines the name to search for
  24721. * @return the found sound or null if not found at all.
  24722. */
  24723. Scene.prototype.getSoundByName = function (name) {
  24724. var index;
  24725. if (BABYLON.AudioEngine) {
  24726. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24727. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24728. return this.mainSoundTrack.soundCollection[index];
  24729. }
  24730. }
  24731. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24732. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24733. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24734. return this.soundTracks[sdIndex].soundCollection[index];
  24735. }
  24736. }
  24737. }
  24738. }
  24739. return null;
  24740. };
  24741. /**
  24742. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  24743. * @param id defines the id to search for
  24744. * @return the found skeleton or null if not found at all.
  24745. */
  24746. Scene.prototype.getLastSkeletonByID = function (id) {
  24747. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24748. if (this.skeletons[index].id === id) {
  24749. return this.skeletons[index];
  24750. }
  24751. }
  24752. return null;
  24753. };
  24754. /**
  24755. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  24756. * @param id defines the id to search for
  24757. * @return the found skeleton or null if not found at all.
  24758. */
  24759. Scene.prototype.getSkeletonById = function (id) {
  24760. for (var index = 0; index < this.skeletons.length; index++) {
  24761. if (this.skeletons[index].id === id) {
  24762. return this.skeletons[index];
  24763. }
  24764. }
  24765. return null;
  24766. };
  24767. /**
  24768. * Gets a skeleton using a given name
  24769. * @param name defines the name to search for
  24770. * @return the found skeleton or null if not found at all.
  24771. */
  24772. Scene.prototype.getSkeletonByName = function (name) {
  24773. for (var index = 0; index < this.skeletons.length; index++) {
  24774. if (this.skeletons[index].name === name) {
  24775. return this.skeletons[index];
  24776. }
  24777. }
  24778. return null;
  24779. };
  24780. /**
  24781. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  24782. * @param id defines the id to search for
  24783. * @return the found morph target manager or null if not found at all.
  24784. */
  24785. Scene.prototype.getMorphTargetManagerById = function (id) {
  24786. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24787. if (this.morphTargetManagers[index].uniqueId === id) {
  24788. return this.morphTargetManagers[index];
  24789. }
  24790. }
  24791. return null;
  24792. };
  24793. /**
  24794. * Gets a boolean indicating if the given mesh is active
  24795. * @param mesh defines the mesh to look for
  24796. * @returns true if the mesh is in the active list
  24797. */
  24798. Scene.prototype.isActiveMesh = function (mesh) {
  24799. return (this._activeMeshes.indexOf(mesh) !== -1);
  24800. };
  24801. /**
  24802. * Return a the first highlight layer of the scene with a given name.
  24803. * @param name The name of the highlight layer to look for.
  24804. * @return The highlight layer if found otherwise null.
  24805. */
  24806. Scene.prototype.getHighlightLayerByName = function (name) {
  24807. for (var index = 0; index < this.effectLayers.length; index++) {
  24808. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24809. return this.effectLayers[index];
  24810. }
  24811. }
  24812. return null;
  24813. };
  24814. /**
  24815. * Return a the first highlight layer of the scene with a given name.
  24816. * @param name The name of the highlight layer to look for.
  24817. * @return The highlight layer if found otherwise null.
  24818. */
  24819. Scene.prototype.getGlowLayerByName = function (name) {
  24820. for (var index = 0; index < this.effectLayers.length; index++) {
  24821. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24822. return this.effectLayers[index];
  24823. }
  24824. }
  24825. return null;
  24826. };
  24827. Object.defineProperty(Scene.prototype, "uid", {
  24828. /**
  24829. * Return a unique id as a string which can serve as an identifier for the scene
  24830. */
  24831. get: function () {
  24832. if (!this._uid) {
  24833. this._uid = BABYLON.Tools.RandomId();
  24834. }
  24835. return this._uid;
  24836. },
  24837. enumerable: true,
  24838. configurable: true
  24839. });
  24840. /**
  24841. * Add an externaly attached data from its key.
  24842. * This method call will fail and return false, if such key already exists.
  24843. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24844. * @param key the unique key that identifies the data
  24845. * @param data the data object to associate to the key for this Engine instance
  24846. * @return true if no such key were already present and the data was added successfully, false otherwise
  24847. */
  24848. Scene.prototype.addExternalData = function (key, data) {
  24849. if (!this._externalData) {
  24850. this._externalData = new BABYLON.StringDictionary();
  24851. }
  24852. return this._externalData.add(key, data);
  24853. };
  24854. /**
  24855. * Get an externaly attached data from its key
  24856. * @param key the unique key that identifies the data
  24857. * @return the associated data, if present (can be null), or undefined if not present
  24858. */
  24859. Scene.prototype.getExternalData = function (key) {
  24860. if (!this._externalData) {
  24861. return null;
  24862. }
  24863. return this._externalData.get(key);
  24864. };
  24865. /**
  24866. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24867. * @param key the unique key that identifies the data
  24868. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24869. * @return the associated data, can be null if the factory returned null.
  24870. */
  24871. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24872. if (!this._externalData) {
  24873. this._externalData = new BABYLON.StringDictionary();
  24874. }
  24875. return this._externalData.getOrAddWithFactory(key, factory);
  24876. };
  24877. /**
  24878. * Remove an externaly attached data from the Engine instance
  24879. * @param key the unique key that identifies the data
  24880. * @return true if the data was successfully removed, false if it doesn't exist
  24881. */
  24882. Scene.prototype.removeExternalData = function (key) {
  24883. return this._externalData.remove(key);
  24884. };
  24885. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24886. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24887. if (mesh.showSubMeshesBoundingBox) {
  24888. var boundingInfo = subMesh.getBoundingInfo();
  24889. if (boundingInfo !== null && boundingInfo !== undefined) {
  24890. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24891. }
  24892. }
  24893. var material = subMesh.getMaterial();
  24894. if (material !== null && material !== undefined) {
  24895. // Render targets
  24896. if (material.getRenderTargetTextures !== undefined) {
  24897. if (this._processedMaterials.indexOf(material) === -1) {
  24898. this._processedMaterials.push(material);
  24899. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24900. }
  24901. }
  24902. // Dispatch
  24903. this._activeIndices.addCount(subMesh.indexCount, false);
  24904. this._renderingManager.dispatch(subMesh, mesh, material);
  24905. }
  24906. }
  24907. };
  24908. /**
  24909. * Clear the processed materials smart array preventing retention point in material dispose.
  24910. */
  24911. Scene.prototype.freeProcessedMaterials = function () {
  24912. this._processedMaterials.dispose();
  24913. };
  24914. /**
  24915. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24916. */
  24917. Scene.prototype.freeActiveMeshes = function () {
  24918. this._activeMeshes.dispose();
  24919. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24920. this.activeCamera._activeMeshes.dispose();
  24921. }
  24922. if (this.activeCameras) {
  24923. for (var i = 0; i < this.activeCameras.length; i++) {
  24924. var activeCamera = this.activeCameras[i];
  24925. if (activeCamera && activeCamera._activeMeshes) {
  24926. activeCamera._activeMeshes.dispose();
  24927. }
  24928. }
  24929. }
  24930. };
  24931. /**
  24932. * Clear the info related to rendering groups preventing retention points during dispose.
  24933. */
  24934. Scene.prototype.freeRenderingGroups = function () {
  24935. if (this._renderingManager) {
  24936. this._renderingManager.freeRenderingGroups();
  24937. }
  24938. if (this.textures) {
  24939. for (var i = 0; i < this.textures.length; i++) {
  24940. var texture = this.textures[i];
  24941. if (texture && texture.renderList) {
  24942. texture.freeRenderingGroups();
  24943. }
  24944. }
  24945. }
  24946. };
  24947. /** @ignore */
  24948. Scene.prototype._isInIntermediateRendering = function () {
  24949. return this._intermediateRendering;
  24950. };
  24951. /**
  24952. * Defines the current active mesh candidate provider
  24953. * @param provider defines the provider to use
  24954. */
  24955. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24956. this._activeMeshCandidateProvider = provider;
  24957. };
  24958. /**
  24959. * Gets the current active mesh candidate provider
  24960. * @returns the current active mesh candidate provider
  24961. */
  24962. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24963. return this._activeMeshCandidateProvider;
  24964. };
  24965. /**
  24966. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24967. * @returns the current scene
  24968. */
  24969. Scene.prototype.freezeActiveMeshes = function () {
  24970. if (!this.activeCamera) {
  24971. return this;
  24972. }
  24973. if (!this._frustumPlanes) {
  24974. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24975. }
  24976. this._evaluateActiveMeshes();
  24977. this._activeMeshesFrozen = true;
  24978. return this;
  24979. };
  24980. /**
  24981. * Use this function to restart evaluating active meshes on every frame
  24982. * @returns the current scene
  24983. */
  24984. Scene.prototype.unfreezeActiveMeshes = function () {
  24985. this._activeMeshesFrozen = false;
  24986. return this;
  24987. };
  24988. Scene.prototype._evaluateActiveMeshes = function () {
  24989. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24990. return;
  24991. }
  24992. if (!this.activeCamera) {
  24993. return;
  24994. }
  24995. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24996. this.activeCamera._activeMeshes.reset();
  24997. this._activeMeshes.reset();
  24998. this._renderingManager.reset();
  24999. this._processedMaterials.reset();
  25000. this._activeParticleSystems.reset();
  25001. this._activeSkeletons.reset();
  25002. this._softwareSkinnedMeshes.reset();
  25003. if (this._boundingBoxRenderer) {
  25004. this._boundingBoxRenderer.reset();
  25005. }
  25006. // Meshes
  25007. var meshes;
  25008. var len;
  25009. var checkIsEnabled = true;
  25010. // Determine mesh candidates
  25011. if (this._activeMeshCandidateProvider !== undefined) {
  25012. // Use _activeMeshCandidateProvider
  25013. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  25014. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  25015. if (meshes !== undefined) {
  25016. len = meshes.length;
  25017. }
  25018. else {
  25019. len = 0;
  25020. }
  25021. }
  25022. else if (this._selectionOctree !== undefined) {
  25023. // Octree
  25024. var selection = this._selectionOctree.select(this._frustumPlanes);
  25025. meshes = selection.data;
  25026. len = selection.length;
  25027. }
  25028. else {
  25029. // Full scene traversal
  25030. len = this.meshes.length;
  25031. meshes = this.meshes;
  25032. }
  25033. // Check each mesh
  25034. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  25035. mesh = meshes[meshIndex];
  25036. if (mesh.isBlocked) {
  25037. continue;
  25038. }
  25039. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  25040. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  25041. continue;
  25042. }
  25043. mesh.computeWorldMatrix();
  25044. // Intersections
  25045. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  25046. this._meshesForIntersections.pushNoDuplicate(mesh);
  25047. }
  25048. // Switch to current LOD
  25049. meshLOD = mesh.getLOD(this.activeCamera);
  25050. if (meshLOD === undefined || meshLOD === null) {
  25051. continue;
  25052. }
  25053. mesh._preActivate();
  25054. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  25055. this._activeMeshes.push(mesh);
  25056. this.activeCamera._activeMeshes.push(mesh);
  25057. mesh._activate(this._renderId);
  25058. if (meshLOD !== mesh) {
  25059. meshLOD._activate(this._renderId);
  25060. }
  25061. this._activeMesh(mesh, meshLOD);
  25062. }
  25063. }
  25064. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  25065. // Particle systems
  25066. if (this.particlesEnabled) {
  25067. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  25068. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  25069. var particleSystem = this.particleSystems[particleIndex];
  25070. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  25071. continue;
  25072. }
  25073. var emitter = particleSystem.emitter;
  25074. if (!emitter.position || emitter.isEnabled()) {
  25075. this._activeParticleSystems.push(particleSystem);
  25076. particleSystem.animate();
  25077. this._renderingManager.dispatchParticles(particleSystem);
  25078. }
  25079. }
  25080. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  25081. }
  25082. };
  25083. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  25084. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  25085. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  25086. mesh.skeleton.prepare();
  25087. }
  25088. if (!mesh.computeBonesUsingShaders) {
  25089. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  25090. }
  25091. }
  25092. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  25093. var boundingInfo = sourceMesh.getBoundingInfo();
  25094. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  25095. }
  25096. if (mesh !== undefined && mesh !== null
  25097. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  25098. // Submeshes Octrees
  25099. var len;
  25100. var subMeshes;
  25101. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  25102. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  25103. len = intersections.length;
  25104. subMeshes = intersections.data;
  25105. }
  25106. else {
  25107. subMeshes = mesh.subMeshes;
  25108. len = subMeshes.length;
  25109. }
  25110. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  25111. subMesh = subMeshes[subIndex];
  25112. this._evaluateSubMesh(subMesh, mesh);
  25113. }
  25114. }
  25115. };
  25116. /**
  25117. * Update the transform matrix to update from the current active camera
  25118. * @param force defines a boolean used to force the update even if cache is up to date
  25119. */
  25120. Scene.prototype.updateTransformMatrix = function (force) {
  25121. if (!this.activeCamera) {
  25122. return;
  25123. }
  25124. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  25125. };
  25126. /**
  25127. * 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)
  25128. * @param alternateCamera defines the camera to use
  25129. */
  25130. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  25131. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  25132. };
  25133. Scene.prototype._renderForCamera = function (camera, rigParent) {
  25134. if (camera && camera._skipRendering) {
  25135. return;
  25136. }
  25137. var engine = this._engine;
  25138. this.activeCamera = camera;
  25139. if (!this.activeCamera)
  25140. throw new Error("Active camera not set");
  25141. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  25142. // Viewport
  25143. engine.setViewport(this.activeCamera.viewport);
  25144. // Camera
  25145. this.resetCachedMaterial();
  25146. this._renderId++;
  25147. this.updateTransformMatrix();
  25148. if (camera._alternateCamera) {
  25149. this.updateAlternateTransformMatrix(camera._alternateCamera);
  25150. this._alternateRendering = true;
  25151. }
  25152. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  25153. // Meshes
  25154. this._evaluateActiveMeshes();
  25155. // Software skinning
  25156. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  25157. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  25158. mesh.applySkeleton(mesh.skeleton);
  25159. }
  25160. // Render targets
  25161. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  25162. var needsRestoreFrameBuffer = false;
  25163. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  25164. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  25165. }
  25166. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  25167. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  25168. }
  25169. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  25170. this._intermediateRendering = true;
  25171. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  25172. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  25173. var renderTarget = this._renderTargets.data[renderIndex];
  25174. if (renderTarget._shouldRender()) {
  25175. this._renderId++;
  25176. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  25177. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  25178. }
  25179. }
  25180. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  25181. this._intermediateRendering = false;
  25182. this._renderId++;
  25183. needsRestoreFrameBuffer = true; // Restore back buffer
  25184. }
  25185. // Render EffecttLayer Texture
  25186. var stencilState = this._engine.getStencilBuffer();
  25187. var renderEffects = false;
  25188. var needStencil = false;
  25189. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  25190. this._intermediateRendering = true;
  25191. for (var i = 0; i < this.effectLayers.length; i++) {
  25192. var effectLayer = this.effectLayers[i];
  25193. if (effectLayer.shouldRender() &&
  25194. (!effectLayer.camera ||
  25195. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  25196. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  25197. renderEffects = true;
  25198. needStencil = needStencil || effectLayer.needStencil();
  25199. var renderTarget = effectLayer._mainTexture;
  25200. if (renderTarget._shouldRender()) {
  25201. this._renderId++;
  25202. renderTarget.render(false, false);
  25203. needsRestoreFrameBuffer = true;
  25204. }
  25205. }
  25206. }
  25207. this._intermediateRendering = false;
  25208. this._renderId++;
  25209. }
  25210. if (needsRestoreFrameBuffer) {
  25211. engine.restoreDefaultFramebuffer(); // Restore back buffer
  25212. }
  25213. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  25214. // Prepare Frame
  25215. this.postProcessManager._prepareFrame();
  25216. // Backgrounds
  25217. var layerIndex;
  25218. var layer;
  25219. if (this.layers.length) {
  25220. engine.setDepthBuffer(false);
  25221. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  25222. layer = this.layers[layerIndex];
  25223. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  25224. layer.render();
  25225. }
  25226. }
  25227. engine.setDepthBuffer(true);
  25228. }
  25229. // Activate effect Layer stencil
  25230. if (needStencil) {
  25231. this._engine.setStencilBuffer(true);
  25232. }
  25233. // Render
  25234. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  25235. this._renderingManager.render(null, null, true, true);
  25236. this.onAfterDrawPhaseObservable.notifyObservers(this);
  25237. // Restore effect Layer stencil
  25238. if (needStencil) {
  25239. this._engine.setStencilBuffer(stencilState);
  25240. }
  25241. // Bounding boxes
  25242. if (this._boundingBoxRenderer) {
  25243. this._boundingBoxRenderer.render();
  25244. }
  25245. // Lens flares
  25246. if (this.lensFlaresEnabled) {
  25247. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  25248. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  25249. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  25250. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  25251. lensFlareSystem.render();
  25252. }
  25253. }
  25254. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  25255. }
  25256. // Effect Layer
  25257. if (renderEffects) {
  25258. engine.setDepthBuffer(false);
  25259. for (var i = 0; i < this.effectLayers.length; i++) {
  25260. if (this.effectLayers[i].shouldRender()) {
  25261. this.effectLayers[i].render();
  25262. }
  25263. }
  25264. engine.setDepthBuffer(true);
  25265. }
  25266. // Foregrounds
  25267. if (this.layers.length) {
  25268. engine.setDepthBuffer(false);
  25269. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  25270. layer = this.layers[layerIndex];
  25271. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  25272. layer.render();
  25273. }
  25274. }
  25275. engine.setDepthBuffer(true);
  25276. }
  25277. // Finalize frame
  25278. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  25279. // Reset some special arrays
  25280. this._renderTargets.reset();
  25281. this._alternateRendering = false;
  25282. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  25283. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  25284. };
  25285. Scene.prototype._processSubCameras = function (camera) {
  25286. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  25287. this._renderForCamera(camera);
  25288. return;
  25289. }
  25290. // rig cameras
  25291. for (var index = 0; index < camera._rigCameras.length; index++) {
  25292. this._renderForCamera(camera._rigCameras[index], camera);
  25293. }
  25294. this.activeCamera = camera;
  25295. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  25296. };
  25297. Scene.prototype._checkIntersections = function () {
  25298. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  25299. var sourceMesh = this._meshesForIntersections.data[index];
  25300. if (!sourceMesh.actionManager) {
  25301. continue;
  25302. }
  25303. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  25304. var action = sourceMesh.actionManager.actions[actionIndex];
  25305. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25306. var parameters = action.getTriggerParameter();
  25307. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  25308. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  25309. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  25310. if (areIntersecting && currentIntersectionInProgress === -1) {
  25311. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  25312. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  25313. sourceMesh._intersectionsInProgress.push(otherMesh);
  25314. }
  25315. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25316. sourceMesh._intersectionsInProgress.push(otherMesh);
  25317. }
  25318. }
  25319. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  25320. //They intersected, and now they don't.
  25321. //is this trigger an exit trigger? execute an event.
  25322. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25323. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  25324. }
  25325. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  25326. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  25327. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  25328. }
  25329. }
  25330. }
  25331. }
  25332. }
  25333. };
  25334. /**
  25335. * Render the scene
  25336. */
  25337. Scene.prototype.render = function () {
  25338. if (this.isDisposed) {
  25339. return;
  25340. }
  25341. this._activeParticles.fetchNewFrame();
  25342. this._totalVertices.fetchNewFrame();
  25343. this._activeIndices.fetchNewFrame();
  25344. this._activeBones.fetchNewFrame();
  25345. this._meshesForIntersections.reset();
  25346. this.resetCachedMaterial();
  25347. this.onBeforeAnimationsObservable.notifyObservers(this);
  25348. // Actions
  25349. if (this.actionManager) {
  25350. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  25351. }
  25352. //Simplification Queue
  25353. if (this.simplificationQueue && !this.simplificationQueue.running) {
  25354. this.simplificationQueue.executeNext();
  25355. }
  25356. if (this._engine.isDeterministicLockStep()) {
  25357. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  25358. var defaultFPS = (60.0 / 1000.0);
  25359. var defaultFrameTime = 1000 / 60; // frame time in MS
  25360. if (this._physicsEngine) {
  25361. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  25362. }
  25363. var stepsTaken = 0;
  25364. var maxSubSteps = this._engine.getLockstepMaxSteps();
  25365. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  25366. internalSteps = Math.min(internalSteps, maxSubSteps);
  25367. do {
  25368. this.onBeforeStepObservable.notifyObservers(this);
  25369. // Animations
  25370. this._animationRatio = defaultFrameTime * defaultFPS;
  25371. this._animate();
  25372. this.onAfterAnimationsObservable.notifyObservers(this);
  25373. // Physics
  25374. if (this._physicsEngine) {
  25375. this.onBeforePhysicsObservable.notifyObservers(this);
  25376. this._physicsEngine._step(defaultFrameTime / 1000);
  25377. this.onAfterPhysicsObservable.notifyObservers(this);
  25378. }
  25379. this.onAfterStepObservable.notifyObservers(this);
  25380. this._currentStepId++;
  25381. stepsTaken++;
  25382. deltaTime -= defaultFrameTime;
  25383. } while (deltaTime > 0 && stepsTaken < internalSteps);
  25384. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  25385. }
  25386. else {
  25387. // Animations
  25388. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  25389. this._animationRatio = deltaTime * (60.0 / 1000.0);
  25390. this._animate();
  25391. this.onAfterAnimationsObservable.notifyObservers(this);
  25392. // Physics
  25393. if (this._physicsEngine) {
  25394. this.onBeforePhysicsObservable.notifyObservers(this);
  25395. this._physicsEngine._step(deltaTime / 1000.0);
  25396. this.onAfterPhysicsObservable.notifyObservers(this);
  25397. }
  25398. }
  25399. // update gamepad manager
  25400. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  25401. this._gamepadManager._checkGamepadsStatus();
  25402. }
  25403. // Update Cameras
  25404. if (this.activeCameras.length > 0) {
  25405. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  25406. var camera = this.activeCameras[cameraIndex];
  25407. camera.update();
  25408. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  25409. // rig cameras
  25410. for (var index = 0; index < camera._rigCameras.length; index++) {
  25411. camera._rigCameras[index].update();
  25412. }
  25413. }
  25414. }
  25415. }
  25416. else if (this.activeCamera) {
  25417. this.activeCamera.update();
  25418. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  25419. // rig cameras
  25420. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  25421. this.activeCamera._rigCameras[index].update();
  25422. }
  25423. }
  25424. }
  25425. // Before render
  25426. this.onBeforeRenderObservable.notifyObservers(this);
  25427. // Customs render targets
  25428. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  25429. var engine = this.getEngine();
  25430. var currentActiveCamera = this.activeCamera;
  25431. if (this.renderTargetsEnabled) {
  25432. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  25433. this._intermediateRendering = true;
  25434. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  25435. var renderTarget = this.customRenderTargets[customIndex];
  25436. if (renderTarget._shouldRender()) {
  25437. this._renderId++;
  25438. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  25439. if (!this.activeCamera)
  25440. throw new Error("Active camera not set");
  25441. // Viewport
  25442. engine.setViewport(this.activeCamera.viewport);
  25443. // Camera
  25444. this.updateTransformMatrix();
  25445. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  25446. }
  25447. }
  25448. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  25449. this._intermediateRendering = false;
  25450. this._renderId++;
  25451. }
  25452. // Restore back buffer
  25453. if (this.customRenderTargets.length > 0) {
  25454. engine.restoreDefaultFramebuffer();
  25455. }
  25456. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  25457. this.activeCamera = currentActiveCamera;
  25458. // Procedural textures
  25459. if (this.proceduralTexturesEnabled) {
  25460. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  25461. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  25462. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  25463. if (proceduralTexture._shouldRender()) {
  25464. proceduralTexture.render();
  25465. }
  25466. }
  25467. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  25468. }
  25469. // Clear
  25470. if (this.autoClearDepthAndStencil || this.autoClear) {
  25471. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  25472. }
  25473. // Shadows
  25474. if (this.shadowsEnabled) {
  25475. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  25476. var light = this.lights[lightIndex];
  25477. var shadowGenerator = light.getShadowGenerator();
  25478. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  25479. var shadowMap = (shadowGenerator.getShadowMap());
  25480. if (this.textures.indexOf(shadowMap) !== -1) {
  25481. this._renderTargets.push(shadowMap);
  25482. }
  25483. }
  25484. }
  25485. }
  25486. // Depth renderer
  25487. for (var key in this._depthRenderer) {
  25488. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  25489. }
  25490. // Geometry renderer
  25491. if (this._geometryBufferRenderer) {
  25492. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  25493. }
  25494. // RenderPipeline
  25495. if (this._postProcessRenderPipelineManager) {
  25496. this._postProcessRenderPipelineManager.update();
  25497. }
  25498. // Multi-cameras?
  25499. if (this.activeCameras.length > 0) {
  25500. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  25501. if (cameraIndex > 0) {
  25502. this._engine.clear(null, false, true, true);
  25503. }
  25504. this._processSubCameras(this.activeCameras[cameraIndex]);
  25505. }
  25506. }
  25507. else {
  25508. if (!this.activeCamera) {
  25509. throw new Error("No camera defined");
  25510. }
  25511. this._processSubCameras(this.activeCamera);
  25512. }
  25513. // Intersection checks
  25514. this._checkIntersections();
  25515. // Update the audio listener attached to the camera
  25516. if (BABYLON.AudioEngine) {
  25517. this._updateAudioParameters();
  25518. }
  25519. // After render
  25520. if (this.afterRender) {
  25521. this.afterRender();
  25522. }
  25523. this.onAfterRenderObservable.notifyObservers(this);
  25524. // Cleaning
  25525. for (var index = 0; index < this._toBeDisposed.length; index++) {
  25526. var data = this._toBeDisposed.data[index];
  25527. if (data) {
  25528. data.dispose();
  25529. }
  25530. this._toBeDisposed[index] = null;
  25531. }
  25532. this._toBeDisposed.reset();
  25533. if (this.dumpNextRenderTargets) {
  25534. this.dumpNextRenderTargets = false;
  25535. }
  25536. this._activeBones.addCount(0, true);
  25537. this._activeIndices.addCount(0, true);
  25538. this._activeParticles.addCount(0, true);
  25539. };
  25540. Scene.prototype._updateAudioParameters = function () {
  25541. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  25542. return;
  25543. }
  25544. var listeningCamera;
  25545. var audioEngine = BABYLON.Engine.audioEngine;
  25546. if (this.activeCameras.length > 0) {
  25547. listeningCamera = this.activeCameras[0];
  25548. }
  25549. else {
  25550. listeningCamera = this.activeCamera;
  25551. }
  25552. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  25553. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  25554. // for VR cameras
  25555. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  25556. listeningCamera = listeningCamera.rigCameras[0];
  25557. }
  25558. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  25559. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  25560. cameraDirection.normalize();
  25561. // To avoid some errors on GearVR
  25562. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  25563. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  25564. }
  25565. var i;
  25566. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25567. var sound = this.mainSoundTrack.soundCollection[i];
  25568. if (sound.useCustomAttenuation) {
  25569. sound.updateDistanceFromListener();
  25570. }
  25571. }
  25572. for (i = 0; i < this.soundTracks.length; i++) {
  25573. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25574. sound = this.soundTracks[i].soundCollection[j];
  25575. if (sound.useCustomAttenuation) {
  25576. sound.updateDistanceFromListener();
  25577. }
  25578. }
  25579. }
  25580. }
  25581. };
  25582. Object.defineProperty(Scene.prototype, "audioEnabled", {
  25583. // Audio
  25584. /**
  25585. * Gets or sets if audio support is enabled
  25586. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  25587. */
  25588. get: function () {
  25589. return this._audioEnabled;
  25590. },
  25591. set: function (value) {
  25592. this._audioEnabled = value;
  25593. if (BABYLON.AudioEngine) {
  25594. if (this._audioEnabled) {
  25595. this._enableAudio();
  25596. }
  25597. else {
  25598. this._disableAudio();
  25599. }
  25600. }
  25601. },
  25602. enumerable: true,
  25603. configurable: true
  25604. });
  25605. Scene.prototype._disableAudio = function () {
  25606. var i;
  25607. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25608. this.mainSoundTrack.soundCollection[i].pause();
  25609. }
  25610. for (i = 0; i < this.soundTracks.length; i++) {
  25611. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25612. this.soundTracks[i].soundCollection[j].pause();
  25613. }
  25614. }
  25615. };
  25616. Scene.prototype._enableAudio = function () {
  25617. var i;
  25618. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25619. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25620. this.mainSoundTrack.soundCollection[i].play();
  25621. }
  25622. }
  25623. for (i = 0; i < this.soundTracks.length; i++) {
  25624. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25625. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25626. this.soundTracks[i].soundCollection[j].play();
  25627. }
  25628. }
  25629. }
  25630. };
  25631. Object.defineProperty(Scene.prototype, "headphone", {
  25632. /**
  25633. * Gets or sets if audio will be output to headphones
  25634. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  25635. */
  25636. get: function () {
  25637. return this._headphone;
  25638. },
  25639. set: function (value) {
  25640. this._headphone = value;
  25641. if (BABYLON.AudioEngine) {
  25642. if (this._headphone) {
  25643. this._switchAudioModeForHeadphones();
  25644. }
  25645. else {
  25646. this._switchAudioModeForNormalSpeakers();
  25647. }
  25648. }
  25649. },
  25650. enumerable: true,
  25651. configurable: true
  25652. });
  25653. Scene.prototype._switchAudioModeForHeadphones = function () {
  25654. this.mainSoundTrack.switchPanningModelToHRTF();
  25655. for (var i = 0; i < this.soundTracks.length; i++) {
  25656. this.soundTracks[i].switchPanningModelToHRTF();
  25657. }
  25658. };
  25659. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25660. this.mainSoundTrack.switchPanningModelToEqualPower();
  25661. for (var i = 0; i < this.soundTracks.length; i++) {
  25662. this.soundTracks[i].switchPanningModelToEqualPower();
  25663. }
  25664. };
  25665. /**
  25666. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25667. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25668. * @returns the created depth renderer
  25669. */
  25670. Scene.prototype.enableDepthRenderer = function (camera) {
  25671. camera = camera || this.activeCamera;
  25672. if (!camera) {
  25673. throw "No camera available to enable depth renderer";
  25674. }
  25675. if (!this._depthRenderer[camera.id]) {
  25676. var textureType = 0;
  25677. if (this._engine.getCaps().textureHalfFloatRender) {
  25678. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  25679. }
  25680. else if (this._engine.getCaps().textureFloatRender) {
  25681. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  25682. }
  25683. else {
  25684. throw "Depth renderer does not support int texture type";
  25685. }
  25686. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  25687. }
  25688. return this._depthRenderer[camera.id];
  25689. };
  25690. /**
  25691. * Disables a depth renderer for a given camera
  25692. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25693. */
  25694. Scene.prototype.disableDepthRenderer = function (camera) {
  25695. camera = camera || this.activeCamera;
  25696. if (!camera || !this._depthRenderer[camera.id]) {
  25697. return;
  25698. }
  25699. this._depthRenderer[camera.id].dispose();
  25700. delete this._depthRenderer[camera.id];
  25701. };
  25702. /**
  25703. * Enables a GeometryBufferRender and associates it with the scene
  25704. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  25705. * @returns the GeometryBufferRenderer
  25706. */
  25707. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25708. if (ratio === void 0) { ratio = 1; }
  25709. if (this._geometryBufferRenderer) {
  25710. return this._geometryBufferRenderer;
  25711. }
  25712. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25713. if (!this._geometryBufferRenderer.isSupported) {
  25714. this._geometryBufferRenderer = null;
  25715. }
  25716. return this._geometryBufferRenderer;
  25717. };
  25718. /**
  25719. * Disables the GeometryBufferRender associated with the scene
  25720. */
  25721. Scene.prototype.disableGeometryBufferRenderer = function () {
  25722. if (!this._geometryBufferRenderer) {
  25723. return;
  25724. }
  25725. this._geometryBufferRenderer.dispose();
  25726. this._geometryBufferRenderer = null;
  25727. };
  25728. /**
  25729. * Freeze all materials
  25730. * A frozen material will not be updatable but should be faster to render
  25731. */
  25732. Scene.prototype.freezeMaterials = function () {
  25733. for (var i = 0; i < this.materials.length; i++) {
  25734. this.materials[i].freeze();
  25735. }
  25736. };
  25737. /**
  25738. * Unfreeze all materials
  25739. * A frozen material will not be updatable but should be faster to render
  25740. */
  25741. Scene.prototype.unfreezeMaterials = function () {
  25742. for (var i = 0; i < this.materials.length; i++) {
  25743. this.materials[i].unfreeze();
  25744. }
  25745. };
  25746. /**
  25747. * Releases all held ressources
  25748. */
  25749. Scene.prototype.dispose = function () {
  25750. this.beforeRender = null;
  25751. this.afterRender = null;
  25752. this.skeletons = [];
  25753. this.morphTargetManagers = [];
  25754. this.importedMeshesFiles = new Array();
  25755. this.stopAllAnimations();
  25756. this.resetCachedMaterial();
  25757. for (var key in this._depthRenderer) {
  25758. this._depthRenderer[key].dispose();
  25759. }
  25760. if (this._gamepadManager) {
  25761. this._gamepadManager.dispose();
  25762. this._gamepadManager = null;
  25763. }
  25764. // Smart arrays
  25765. if (this.activeCamera) {
  25766. this.activeCamera._activeMeshes.dispose();
  25767. this.activeCamera = null;
  25768. }
  25769. this._activeMeshes.dispose();
  25770. this._renderingManager.dispose();
  25771. this._processedMaterials.dispose();
  25772. this._activeParticleSystems.dispose();
  25773. this._activeSkeletons.dispose();
  25774. this._softwareSkinnedMeshes.dispose();
  25775. this._renderTargets.dispose();
  25776. this._registeredForLateAnimationBindings.dispose();
  25777. if (this._boundingBoxRenderer) {
  25778. this._boundingBoxRenderer.dispose();
  25779. }
  25780. this._meshesForIntersections.dispose();
  25781. this._toBeDisposed.dispose();
  25782. // Abort active requests
  25783. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25784. var request = _a[_i];
  25785. request.abort();
  25786. }
  25787. // Debug layer
  25788. if (this._debugLayer) {
  25789. this._debugLayer.hide();
  25790. }
  25791. // Events
  25792. this.onDisposeObservable.notifyObservers(this);
  25793. this.onDisposeObservable.clear();
  25794. this.onBeforeRenderObservable.clear();
  25795. this.onAfterRenderObservable.clear();
  25796. this.onBeforeRenderTargetsRenderObservable.clear();
  25797. this.onAfterRenderTargetsRenderObservable.clear();
  25798. this.onAfterStepObservable.clear();
  25799. this.onBeforeStepObservable.clear();
  25800. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25801. this.onAfterActiveMeshesEvaluationObservable.clear();
  25802. this.onBeforeParticlesRenderingObservable.clear();
  25803. this.onAfterParticlesRenderingObservable.clear();
  25804. this.onBeforeSpritesRenderingObservable.clear();
  25805. this.onAfterSpritesRenderingObservable.clear();
  25806. this.onBeforeDrawPhaseObservable.clear();
  25807. this.onAfterDrawPhaseObservable.clear();
  25808. this.onBeforePhysicsObservable.clear();
  25809. this.onAfterPhysicsObservable.clear();
  25810. this.onBeforeAnimationsObservable.clear();
  25811. this.onAfterAnimationsObservable.clear();
  25812. this.onDataLoadedObservable.clear();
  25813. this.detachControl();
  25814. // Release sounds & sounds tracks
  25815. if (BABYLON.AudioEngine) {
  25816. this.disposeSounds();
  25817. }
  25818. // VR Helper
  25819. if (this.VRHelper) {
  25820. this.VRHelper.dispose();
  25821. }
  25822. // Detach cameras
  25823. var canvas = this._engine.getRenderingCanvas();
  25824. if (canvas) {
  25825. var index;
  25826. for (index = 0; index < this.cameras.length; index++) {
  25827. this.cameras[index].detachControl(canvas);
  25828. }
  25829. }
  25830. // Release animation groups
  25831. while (this.animationGroups.length) {
  25832. this.animationGroups[0].dispose();
  25833. }
  25834. // Release lights
  25835. while (this.lights.length) {
  25836. this.lights[0].dispose();
  25837. }
  25838. // Release meshes
  25839. while (this.meshes.length) {
  25840. this.meshes[0].dispose(true);
  25841. }
  25842. while (this.transformNodes.length) {
  25843. this.removeTransformNode(this.transformNodes[0]);
  25844. }
  25845. // Release cameras
  25846. while (this.cameras.length) {
  25847. this.cameras[0].dispose();
  25848. }
  25849. // Release materials
  25850. if (this.defaultMaterial) {
  25851. this.defaultMaterial.dispose();
  25852. }
  25853. while (this.multiMaterials.length) {
  25854. this.multiMaterials[0].dispose();
  25855. }
  25856. while (this.materials.length) {
  25857. this.materials[0].dispose();
  25858. }
  25859. // Release particles
  25860. while (this.particleSystems.length) {
  25861. this.particleSystems[0].dispose();
  25862. }
  25863. // Release sprites
  25864. while (this.spriteManagers.length) {
  25865. this.spriteManagers[0].dispose();
  25866. }
  25867. // Release postProcesses
  25868. while (this.postProcesses.length) {
  25869. this.postProcesses[0].dispose();
  25870. }
  25871. // Release layers
  25872. while (this.layers.length) {
  25873. this.layers[0].dispose();
  25874. }
  25875. while (this.effectLayers.length) {
  25876. this.effectLayers[0].dispose();
  25877. }
  25878. // Release textures
  25879. while (this.textures.length) {
  25880. this.textures[0].dispose();
  25881. }
  25882. // Release UBO
  25883. this._sceneUbo.dispose();
  25884. if (this._alternateSceneUbo) {
  25885. this._alternateSceneUbo.dispose();
  25886. }
  25887. // Post-processes
  25888. this.postProcessManager.dispose();
  25889. if (this._postProcessRenderPipelineManager) {
  25890. this._postProcessRenderPipelineManager.dispose();
  25891. }
  25892. // Physics
  25893. if (this._physicsEngine) {
  25894. this.disablePhysicsEngine();
  25895. }
  25896. // Remove from engine
  25897. index = this._engine.scenes.indexOf(this);
  25898. if (index > -1) {
  25899. this._engine.scenes.splice(index, 1);
  25900. }
  25901. this._engine.wipeCaches(true);
  25902. this._isDisposed = true;
  25903. };
  25904. Object.defineProperty(Scene.prototype, "isDisposed", {
  25905. /**
  25906. * Gets if the scene is already disposed
  25907. */
  25908. get: function () {
  25909. return this._isDisposed;
  25910. },
  25911. enumerable: true,
  25912. configurable: true
  25913. });
  25914. /**
  25915. * Releases sounds & soundtracks
  25916. */
  25917. Scene.prototype.disposeSounds = function () {
  25918. if (!this._mainSoundTrack) {
  25919. return;
  25920. }
  25921. this.mainSoundTrack.dispose();
  25922. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25923. this.soundTracks[scIndex].dispose();
  25924. }
  25925. };
  25926. // Octrees
  25927. /**
  25928. * Get the world extend vectors with an optional filter
  25929. *
  25930. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25931. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25932. */
  25933. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25934. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25935. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25936. filterPredicate = filterPredicate || (function () { return true; });
  25937. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25938. mesh.computeWorldMatrix(true);
  25939. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25940. return;
  25941. }
  25942. var boundingInfo = mesh.getBoundingInfo();
  25943. var minBox = boundingInfo.boundingBox.minimumWorld;
  25944. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25945. BABYLON.Tools.CheckExtends(minBox, min, max);
  25946. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25947. });
  25948. return {
  25949. min: min,
  25950. max: max
  25951. };
  25952. };
  25953. /**
  25954. * Creates or updates the octree used to boost selection (picking)
  25955. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25956. * @param maxCapacity defines the maximum capacity per leaf
  25957. * @param maxDepth defines the maximum depth of the octree
  25958. * @returns an octree of AbstractMesh
  25959. */
  25960. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25961. if (maxCapacity === void 0) { maxCapacity = 64; }
  25962. if (maxDepth === void 0) { maxDepth = 2; }
  25963. if (!this._selectionOctree) {
  25964. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25965. }
  25966. var worldExtends = this.getWorldExtends();
  25967. // Update octree
  25968. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25969. return this._selectionOctree;
  25970. };
  25971. // Picking
  25972. /**
  25973. * Creates a ray that can be used to pick in the scene
  25974. * @param x defines the x coordinate of the origin (on-screen)
  25975. * @param y defines the y coordinate of the origin (on-screen)
  25976. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  25977. * @param camera defines the camera to use for the picking
  25978. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  25979. * @returns a Ray
  25980. */
  25981. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25982. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25983. var result = BABYLON.Ray.Zero();
  25984. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25985. return result;
  25986. };
  25987. /**
  25988. * Creates a ray that can be used to pick in the scene
  25989. * @param x defines the x coordinate of the origin (on-screen)
  25990. * @param y defines the y coordinate of the origin (on-screen)
  25991. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  25992. * @param result defines the ray where to store the picking ray
  25993. * @param camera defines the camera to use for the picking
  25994. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  25995. * @returns the current scene
  25996. */
  25997. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25998. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25999. var engine = this._engine;
  26000. if (!camera) {
  26001. if (!this.activeCamera)
  26002. throw new Error("Active camera not set");
  26003. camera = this.activeCamera;
  26004. }
  26005. var cameraViewport = camera.viewport;
  26006. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  26007. // Moving coordinates to local viewport world
  26008. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  26009. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  26010. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  26011. return this;
  26012. };
  26013. /**
  26014. * Creates a ray that can be used to pick in the scene
  26015. * @param x defines the x coordinate of the origin (on-screen)
  26016. * @param y defines the y coordinate of the origin (on-screen)
  26017. * @param camera defines the camera to use for the picking
  26018. * @returns a Ray
  26019. */
  26020. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  26021. var result = BABYLON.Ray.Zero();
  26022. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  26023. return result;
  26024. };
  26025. /**
  26026. * Creates a ray that can be used to pick in the scene
  26027. * @param x defines the x coordinate of the origin (on-screen)
  26028. * @param y defines the y coordinate of the origin (on-screen)
  26029. * @param result defines the ray where to store the picking ray
  26030. * @param camera defines the camera to use for the picking
  26031. * @returns the current scene
  26032. */
  26033. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  26034. if (!BABYLON.PickingInfo) {
  26035. return this;
  26036. }
  26037. var engine = this._engine;
  26038. if (!camera) {
  26039. if (!this.activeCamera)
  26040. throw new Error("Active camera not set");
  26041. camera = this.activeCamera;
  26042. }
  26043. var cameraViewport = camera.viewport;
  26044. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  26045. var identity = BABYLON.Matrix.Identity();
  26046. // Moving coordinates to local viewport world
  26047. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  26048. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  26049. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  26050. return this;
  26051. };
  26052. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  26053. if (!BABYLON.PickingInfo) {
  26054. return null;
  26055. }
  26056. var pickingInfo = null;
  26057. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  26058. var mesh = this.meshes[meshIndex];
  26059. if (predicate) {
  26060. if (!predicate(mesh)) {
  26061. continue;
  26062. }
  26063. }
  26064. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  26065. continue;
  26066. }
  26067. var world = mesh.getWorldMatrix();
  26068. var ray = rayFunction(world);
  26069. var result = mesh.intersects(ray, fastCheck);
  26070. if (!result || !result.hit)
  26071. continue;
  26072. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  26073. continue;
  26074. pickingInfo = result;
  26075. if (fastCheck) {
  26076. break;
  26077. }
  26078. }
  26079. return pickingInfo || new BABYLON.PickingInfo();
  26080. };
  26081. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  26082. if (!BABYLON.PickingInfo) {
  26083. return null;
  26084. }
  26085. var pickingInfos = new Array();
  26086. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  26087. var mesh = this.meshes[meshIndex];
  26088. if (predicate) {
  26089. if (!predicate(mesh)) {
  26090. continue;
  26091. }
  26092. }
  26093. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  26094. continue;
  26095. }
  26096. var world = mesh.getWorldMatrix();
  26097. var ray = rayFunction(world);
  26098. var result = mesh.intersects(ray, false);
  26099. if (!result || !result.hit)
  26100. continue;
  26101. pickingInfos.push(result);
  26102. }
  26103. return pickingInfos;
  26104. };
  26105. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  26106. if (!BABYLON.PickingInfo) {
  26107. return null;
  26108. }
  26109. var pickingInfo = null;
  26110. if (!camera) {
  26111. if (!this.activeCamera) {
  26112. return null;
  26113. }
  26114. camera = this.activeCamera;
  26115. }
  26116. if (this.spriteManagers.length > 0) {
  26117. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  26118. var spriteManager = this.spriteManagers[spriteIndex];
  26119. if (!spriteManager.isPickable) {
  26120. continue;
  26121. }
  26122. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  26123. if (!result || !result.hit)
  26124. continue;
  26125. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  26126. continue;
  26127. pickingInfo = result;
  26128. if (fastCheck) {
  26129. break;
  26130. }
  26131. }
  26132. }
  26133. return pickingInfo || new BABYLON.PickingInfo();
  26134. };
  26135. /** Launch a ray to try to pick a mesh in the scene
  26136. * @param x position on screen
  26137. * @param y position on screen
  26138. * @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
  26139. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  26140. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  26141. * @returns a PickingInfo
  26142. */
  26143. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  26144. var _this = this;
  26145. if (!BABYLON.PickingInfo) {
  26146. return null;
  26147. }
  26148. return this._internalPick(function (world) {
  26149. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  26150. return _this._tempPickingRay;
  26151. }, predicate, fastCheck);
  26152. };
  26153. /** Launch a ray to try to pick a sprite in the scene
  26154. * @param x position on screen
  26155. * @param y position on screen
  26156. * @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
  26157. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  26158. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  26159. * @returns a PickingInfo
  26160. */
  26161. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  26162. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  26163. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  26164. };
  26165. /** Use the given ray to pick a mesh in the scene
  26166. * @param ray The ray to use to pick meshes
  26167. * @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
  26168. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  26169. * @returns a PickingInfo
  26170. */
  26171. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  26172. var _this = this;
  26173. return this._internalPick(function (world) {
  26174. if (!_this._pickWithRayInverseMatrix) {
  26175. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  26176. }
  26177. world.invertToRef(_this._pickWithRayInverseMatrix);
  26178. if (!_this._cachedRayForTransform) {
  26179. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  26180. }
  26181. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  26182. return _this._cachedRayForTransform;
  26183. }, predicate, fastCheck);
  26184. };
  26185. /**
  26186. * Launch a ray to try to pick a mesh in the scene
  26187. * @param x X position on screen
  26188. * @param y Y position on screen
  26189. * @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
  26190. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  26191. * @returns an array of PickingInfo
  26192. */
  26193. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  26194. var _this = this;
  26195. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  26196. };
  26197. /**
  26198. * Launch a ray to try to pick a mesh in the scene
  26199. * @param ray Ray to use
  26200. * @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
  26201. * @returns an array of PickingInfo
  26202. */
  26203. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  26204. var _this = this;
  26205. return this._internalMultiPick(function (world) {
  26206. if (!_this._pickWithRayInverseMatrix) {
  26207. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  26208. }
  26209. world.invertToRef(_this._pickWithRayInverseMatrix);
  26210. if (!_this._cachedRayForTransform) {
  26211. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  26212. }
  26213. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  26214. return _this._cachedRayForTransform;
  26215. }, predicate);
  26216. };
  26217. /**
  26218. * Force the value of meshUnderPointer
  26219. * @param mesh defines the mesh to use
  26220. */
  26221. Scene.prototype.setPointerOverMesh = function (mesh) {
  26222. if (this._pointerOverMesh === mesh) {
  26223. return;
  26224. }
  26225. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  26226. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  26227. }
  26228. this._pointerOverMesh = mesh;
  26229. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  26230. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  26231. }
  26232. };
  26233. /**
  26234. * Gets the mesh under the pointer
  26235. * @returns a Mesh or null if no mesh is under the pointer
  26236. */
  26237. Scene.prototype.getPointerOverMesh = function () {
  26238. return this._pointerOverMesh;
  26239. };
  26240. /**
  26241. * Force the sprite under the pointer
  26242. * @param sprite defines the sprite to use
  26243. */
  26244. Scene.prototype.setPointerOverSprite = function (sprite) {
  26245. if (this._pointerOverSprite === sprite) {
  26246. return;
  26247. }
  26248. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  26249. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  26250. }
  26251. this._pointerOverSprite = sprite;
  26252. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  26253. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  26254. }
  26255. };
  26256. /**
  26257. * Gets the sprite under the pointer
  26258. * @returns a Sprite or null if no sprite is under the pointer
  26259. */
  26260. Scene.prototype.getPointerOverSprite = function () {
  26261. return this._pointerOverSprite;
  26262. };
  26263. // Physics
  26264. /**
  26265. * Gets the current physics engine
  26266. * @returns a PhysicsEngine or null if none attached
  26267. */
  26268. Scene.prototype.getPhysicsEngine = function () {
  26269. return this._physicsEngine;
  26270. };
  26271. /**
  26272. * Enables physics to the current scene
  26273. * @param gravity defines the scene's gravity for the physics engine
  26274. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  26275. * @return a boolean indicating if the physics engine was initialized
  26276. */
  26277. Scene.prototype.enablePhysics = function (gravity, plugin) {
  26278. if (gravity === void 0) { gravity = null; }
  26279. if (this._physicsEngine) {
  26280. return true;
  26281. }
  26282. try {
  26283. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  26284. return true;
  26285. }
  26286. catch (e) {
  26287. BABYLON.Tools.Error(e.message);
  26288. return false;
  26289. }
  26290. };
  26291. /**
  26292. * Disables and disposes the physics engine associated with the scene
  26293. */
  26294. Scene.prototype.disablePhysicsEngine = function () {
  26295. if (!this._physicsEngine) {
  26296. return;
  26297. }
  26298. this._physicsEngine.dispose();
  26299. this._physicsEngine = null;
  26300. };
  26301. /**
  26302. * Gets a boolean indicating if there is an active physics engine
  26303. * @returns a boolean indicating if there is an active physics engine
  26304. */
  26305. Scene.prototype.isPhysicsEnabled = function () {
  26306. return this._physicsEngine !== undefined;
  26307. };
  26308. /**
  26309. * Deletes a physics compound impostor
  26310. * @param compound defines the compound to delete
  26311. */
  26312. Scene.prototype.deleteCompoundImpostor = function (compound) {
  26313. var mesh = compound.parts[0].mesh;
  26314. if (mesh.physicsImpostor) {
  26315. mesh.physicsImpostor.dispose();
  26316. mesh.physicsImpostor = null;
  26317. }
  26318. };
  26319. // Misc.
  26320. /** @ignore */
  26321. Scene.prototype._rebuildGeometries = function () {
  26322. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  26323. var geometry = _a[_i];
  26324. geometry._rebuild();
  26325. }
  26326. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  26327. var mesh = _c[_b];
  26328. mesh._rebuild();
  26329. }
  26330. if (this.postProcessManager) {
  26331. this.postProcessManager._rebuild();
  26332. }
  26333. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  26334. var layer = _e[_d];
  26335. layer._rebuild();
  26336. }
  26337. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  26338. var effectLayer = _g[_f];
  26339. effectLayer._rebuild();
  26340. }
  26341. if (this._boundingBoxRenderer) {
  26342. this._boundingBoxRenderer._rebuild();
  26343. }
  26344. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  26345. var system = _j[_h];
  26346. system.rebuild();
  26347. }
  26348. if (this._postProcessRenderPipelineManager) {
  26349. this._postProcessRenderPipelineManager._rebuild();
  26350. }
  26351. };
  26352. /** @ignore */
  26353. Scene.prototype._rebuildTextures = function () {
  26354. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  26355. var texture = _a[_i];
  26356. texture._rebuild();
  26357. }
  26358. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26359. };
  26360. /**
  26361. * Creates a default light for the scene.
  26362. * @param replace Whether to replace the existing lights in the scene.
  26363. */
  26364. Scene.prototype.createDefaultLight = function (replace) {
  26365. if (replace === void 0) { replace = false; }
  26366. // Dispose existing light in replace mode.
  26367. if (replace) {
  26368. if (this.lights) {
  26369. for (var i = 0; i < this.lights.length; i++) {
  26370. this.lights[i].dispose();
  26371. }
  26372. }
  26373. }
  26374. // Light
  26375. if (this.lights.length === 0) {
  26376. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  26377. }
  26378. };
  26379. /**
  26380. * Creates a default camera for the scene.
  26381. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  26382. * @param replace Whether to replace the existing active camera in the scene.
  26383. * @param attachCameraControls Whether to attach camera controls to the canvas.
  26384. */
  26385. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  26386. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  26387. if (replace === void 0) { replace = false; }
  26388. if (attachCameraControls === void 0) { attachCameraControls = false; }
  26389. // Dispose existing camera in replace mode.
  26390. if (replace) {
  26391. if (this.activeCamera) {
  26392. this.activeCamera.dispose();
  26393. this.activeCamera = null;
  26394. }
  26395. }
  26396. // Camera
  26397. if (!this.activeCamera) {
  26398. var worldExtends = this.getWorldExtends();
  26399. var worldSize = worldExtends.max.subtract(worldExtends.min);
  26400. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  26401. var camera;
  26402. var radius = worldSize.length() * 1.5;
  26403. // empty scene scenario!
  26404. if (!isFinite(radius)) {
  26405. radius = 1;
  26406. worldCenter.copyFromFloats(0, 0, 0);
  26407. }
  26408. if (createArcRotateCamera) {
  26409. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  26410. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  26411. arcRotateCamera.wheelPrecision = 100 / radius;
  26412. camera = arcRotateCamera;
  26413. }
  26414. else {
  26415. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  26416. freeCamera.setTarget(worldCenter);
  26417. camera = freeCamera;
  26418. }
  26419. camera.minZ = radius * 0.01;
  26420. camera.maxZ = radius * 1000;
  26421. camera.speed = radius * 0.2;
  26422. this.activeCamera = camera;
  26423. var canvas = this.getEngine().getRenderingCanvas();
  26424. if (attachCameraControls && canvas) {
  26425. camera.attachControl(canvas);
  26426. }
  26427. }
  26428. };
  26429. /**
  26430. * Creates a default camera and a default light
  26431. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  26432. * @param replace defines if the camera and/or light will replace the existing ones
  26433. * @param attachCameraControls defines if attachControl will be called on the new camera
  26434. */
  26435. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  26436. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  26437. if (replace === void 0) { replace = false; }
  26438. if (attachCameraControls === void 0) { attachCameraControls = false; }
  26439. this.createDefaultLight(replace);
  26440. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  26441. };
  26442. /**
  26443. * Creates a new sky box
  26444. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  26445. * @param environmentTexture defines the texture to use as environment texture
  26446. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  26447. * @param scale defines the overall scale of the skybox
  26448. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  26449. * @returns a new mesh holding the sky box
  26450. */
  26451. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  26452. if (pbr === void 0) { pbr = false; }
  26453. if (scale === void 0) { scale = 1000; }
  26454. if (blur === void 0) { blur = 0; }
  26455. if (environmentTexture) {
  26456. this.environmentTexture = environmentTexture;
  26457. }
  26458. if (!this.environmentTexture) {
  26459. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  26460. return null;
  26461. }
  26462. // Skybox
  26463. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  26464. if (pbr) {
  26465. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  26466. hdrSkyboxMaterial.backFaceCulling = false;
  26467. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  26468. if (hdrSkyboxMaterial.reflectionTexture) {
  26469. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  26470. }
  26471. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  26472. hdrSkyboxMaterial.disableLighting = true;
  26473. hdrSkyboxMaterial.twoSidedLighting = true;
  26474. hdrSkybox.infiniteDistance = true;
  26475. hdrSkybox.material = hdrSkyboxMaterial;
  26476. }
  26477. else {
  26478. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  26479. skyboxMaterial.backFaceCulling = false;
  26480. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  26481. if (skyboxMaterial.reflectionTexture) {
  26482. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  26483. }
  26484. skyboxMaterial.disableLighting = true;
  26485. hdrSkybox.infiniteDistance = true;
  26486. hdrSkybox.material = skyboxMaterial;
  26487. }
  26488. return hdrSkybox;
  26489. };
  26490. /**
  26491. * Creates a new environment
  26492. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  26493. * @param options defines the options you can use to configure the environment
  26494. * @returns the new EnvironmentHelper
  26495. */
  26496. Scene.prototype.createDefaultEnvironment = function (options) {
  26497. if (BABYLON.EnvironmentHelper) {
  26498. return new BABYLON.EnvironmentHelper(options, this);
  26499. }
  26500. return null;
  26501. };
  26502. /**
  26503. * Creates a new VREXperienceHelper
  26504. * @see http://doc.babylonjs.com/how_to/webvr_helper
  26505. * @param webVROptions defines the options used to create the new VREXperienceHelper
  26506. * @returns a new VREXperienceHelper
  26507. */
  26508. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  26509. if (webVROptions === void 0) { webVROptions = {}; }
  26510. return new BABYLON.VRExperienceHelper(this, webVROptions);
  26511. };
  26512. // Tags
  26513. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  26514. if (tagsQuery === undefined) {
  26515. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  26516. return list;
  26517. }
  26518. var listByTags = [];
  26519. forEach = forEach || (function (item) { return; });
  26520. for (var i in list) {
  26521. var item = list[i];
  26522. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  26523. listByTags.push(item);
  26524. forEach(item);
  26525. }
  26526. }
  26527. return listByTags;
  26528. };
  26529. /**
  26530. * Get a list of meshes by tags
  26531. * @param tagsQuery defines the tags query to use
  26532. * @param forEach defines a predicate used to filter results
  26533. * @returns an array of Mesh
  26534. */
  26535. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  26536. return this._getByTags(this.meshes, tagsQuery, forEach);
  26537. };
  26538. /**
  26539. * Get a list of cameras by tags
  26540. * @param tagsQuery defines the tags query to use
  26541. * @param forEach defines a predicate used to filter results
  26542. * @returns an array of Camera
  26543. */
  26544. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  26545. return this._getByTags(this.cameras, tagsQuery, forEach);
  26546. };
  26547. /**
  26548. * Get a list of lights by tags
  26549. * @param tagsQuery defines the tags query to use
  26550. * @param forEach defines a predicate used to filter results
  26551. * @returns an array of Light
  26552. */
  26553. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  26554. return this._getByTags(this.lights, tagsQuery, forEach);
  26555. };
  26556. /**
  26557. * Get a list of materials by tags
  26558. * @param tagsQuery defines the tags query to use
  26559. * @param forEach defines a predicate used to filter results
  26560. * @returns an array of Material
  26561. */
  26562. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  26563. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  26564. };
  26565. /**
  26566. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  26567. * This allowed control for front to back rendering or reversly depending of the special needs.
  26568. *
  26569. * @param renderingGroupId The rendering group id corresponding to its index
  26570. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  26571. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  26572. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  26573. */
  26574. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  26575. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  26576. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  26577. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  26578. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  26579. };
  26580. /**
  26581. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  26582. *
  26583. * @param renderingGroupId The rendering group id corresponding to its index
  26584. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  26585. * @param depth Automatically clears depth between groups if true and autoClear is true.
  26586. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  26587. */
  26588. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  26589. if (depth === void 0) { depth = true; }
  26590. if (stencil === void 0) { stencil = true; }
  26591. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  26592. };
  26593. /**
  26594. * Will flag all materials as dirty to trigger new shader compilation
  26595. * @param flag defines the flag used to specify which material part must be marked as dirty
  26596. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  26597. */
  26598. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  26599. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  26600. var material = _a[_i];
  26601. if (predicate && !predicate(material)) {
  26602. continue;
  26603. }
  26604. material.markAsDirty(flag);
  26605. }
  26606. };
  26607. /** @ignore */
  26608. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  26609. var _this = this;
  26610. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  26611. this._activeRequests.push(request);
  26612. request.onCompleteObservable.add(function (request) {
  26613. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  26614. });
  26615. return request;
  26616. };
  26617. /** @ignore */
  26618. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  26619. var _this = this;
  26620. return new Promise(function (resolve, reject) {
  26621. _this._loadFile(url, function (data) {
  26622. resolve(data);
  26623. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  26624. reject(exception);
  26625. });
  26626. });
  26627. };
  26628. // Statics
  26629. Scene._FOGMODE_NONE = 0;
  26630. Scene._FOGMODE_EXP = 1;
  26631. Scene._FOGMODE_EXP2 = 2;
  26632. Scene._FOGMODE_LINEAR = 3;
  26633. Scene._uniqueIdCounter = 0;
  26634. /**
  26635. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  26636. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26637. */
  26638. Scene.MinDeltaTime = 1.0;
  26639. /**
  26640. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  26641. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  26642. */
  26643. Scene.MaxDeltaTime = 1000.0;
  26644. /** The distance in pixel that you have to move to prevent some events */
  26645. Scene.DragMovementThreshold = 10; // in pixels
  26646. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  26647. Scene.LongPressDelay = 500; // in milliseconds
  26648. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  26649. Scene.DoubleClickDelay = 300; // in milliseconds
  26650. /** If you need to check double click without raising a single click at first click, enable this flag */
  26651. Scene.ExclusiveDoubleClickMode = false;
  26652. return Scene;
  26653. }());
  26654. BABYLON.Scene = Scene;
  26655. })(BABYLON || (BABYLON = {}));
  26656. //# sourceMappingURL=babylon.scene.js.map
  26657. "use strict";
  26658. var BABYLON;
  26659. (function (BABYLON) {
  26660. /**
  26661. * Set of assets to keep when moving a scene into an asset container.
  26662. */
  26663. var KeepAssets = /** @class */ (function () {
  26664. function KeepAssets() {
  26665. /**
  26666. * Cameras to keep.
  26667. */
  26668. this.cameras = new Array();
  26669. /**
  26670. * Lights to keep.
  26671. */
  26672. this.lights = new Array();
  26673. /**
  26674. * Meshes to keep.
  26675. */
  26676. this.meshes = new Array();
  26677. /**
  26678. * Skeletons to keep.
  26679. */
  26680. this.skeletons = new Array();
  26681. /**
  26682. * ParticleSystems to keep.
  26683. */
  26684. this.particleSystems = new Array();
  26685. /**
  26686. * Animations to keep.
  26687. */
  26688. this.animations = new Array();
  26689. /**
  26690. * AnimationGroups to keep.
  26691. */
  26692. this.animationGroups = new Array();
  26693. /**
  26694. * MultiMaterials to keep.
  26695. */
  26696. this.multiMaterials = new Array();
  26697. /**
  26698. * Materials to keep.
  26699. */
  26700. this.materials = new Array();
  26701. /**
  26702. * MorphTargetManagers to keep.
  26703. */
  26704. this.morphTargetManagers = new Array();
  26705. /**
  26706. * Geometries to keep.
  26707. */
  26708. this.geometries = new Array();
  26709. /**
  26710. * TransformNodes to keep.
  26711. */
  26712. this.transformNodes = new Array();
  26713. /**
  26714. * LensFlareSystems to keep.
  26715. */
  26716. this.lensFlareSystems = new Array();
  26717. /**
  26718. * ShadowGenerators to keep.
  26719. */
  26720. this.shadowGenerators = new Array();
  26721. /**
  26722. * ActionManagers to keep.
  26723. */
  26724. this.actionManagers = new Array();
  26725. /**
  26726. * Sounds to keep.
  26727. */
  26728. this.sounds = new Array();
  26729. /**
  26730. * Textures to keep.
  26731. */
  26732. this.textures = new Array();
  26733. }
  26734. return KeepAssets;
  26735. }());
  26736. BABYLON.KeepAssets = KeepAssets;
  26737. /**
  26738. * Container with a set of assets that can be added or removed from a scene.
  26739. */
  26740. var AssetContainer = /** @class */ (function () {
  26741. /**
  26742. * Instantiates an AssetContainer.
  26743. * @param scene The scene the AssetContainer belongs to.
  26744. */
  26745. function AssetContainer(scene) {
  26746. // Objects
  26747. /**
  26748. * Cameras populated in the container.
  26749. */
  26750. this.cameras = new Array();
  26751. /**
  26752. * Lights populated in the container.
  26753. */
  26754. this.lights = new Array();
  26755. /**
  26756. * Meshes populated in the container.
  26757. */
  26758. this.meshes = new Array();
  26759. /**
  26760. * Skeletons populated in the container.
  26761. */
  26762. this.skeletons = new Array();
  26763. /**
  26764. * ParticleSystems populated in the container.
  26765. */
  26766. this.particleSystems = new Array();
  26767. /**
  26768. * Animations populated in the container.
  26769. */
  26770. this.animations = new Array();
  26771. /**
  26772. * AnimationGroups populated in the container.
  26773. */
  26774. this.animationGroups = new Array();
  26775. /**
  26776. * MultiMaterials populated in the container.
  26777. */
  26778. this.multiMaterials = new Array();
  26779. /**
  26780. * Materials populated in the container.
  26781. */
  26782. this.materials = new Array();
  26783. /**
  26784. * MorphTargetManagers populated in the container.
  26785. */
  26786. this.morphTargetManagers = new Array();
  26787. /**
  26788. * Geometries populated in the container.
  26789. */
  26790. this.geometries = new Array();
  26791. /**
  26792. * TransformNodes populated in the container.
  26793. */
  26794. this.transformNodes = new Array();
  26795. /**
  26796. * LensFlareSystems populated in the container.
  26797. */
  26798. this.lensFlareSystems = new Array();
  26799. /**
  26800. * ShadowGenerators populated in the container.
  26801. */
  26802. this.shadowGenerators = new Array();
  26803. /**
  26804. * ActionManagers populated in the container.
  26805. */
  26806. this.actionManagers = new Array();
  26807. /**
  26808. * Sounds populated in the container.
  26809. */
  26810. this.sounds = new Array();
  26811. /**
  26812. * Textures populated in the container.
  26813. */
  26814. this.textures = new Array();
  26815. this.scene = scene;
  26816. }
  26817. /**
  26818. * Adds all the assets from the container to the scene.
  26819. */
  26820. AssetContainer.prototype.addAllToScene = function () {
  26821. var _this = this;
  26822. this.cameras.forEach(function (o) {
  26823. _this.scene.addCamera(o);
  26824. });
  26825. this.lights.forEach(function (o) {
  26826. _this.scene.addLight(o);
  26827. });
  26828. this.meshes.forEach(function (o) {
  26829. _this.scene.addMesh(o);
  26830. });
  26831. this.skeletons.forEach(function (o) {
  26832. _this.scene.addSkeleton(o);
  26833. });
  26834. this.particleSystems.forEach(function (o) {
  26835. _this.scene.addParticleSystem(o);
  26836. });
  26837. this.animations.forEach(function (o) {
  26838. _this.scene.addAnimation(o);
  26839. });
  26840. this.animationGroups.forEach(function (o) {
  26841. _this.scene.addAnimationGroup(o);
  26842. });
  26843. this.multiMaterials.forEach(function (o) {
  26844. _this.scene.addMultiMaterial(o);
  26845. });
  26846. this.materials.forEach(function (o) {
  26847. _this.scene.addMaterial(o);
  26848. });
  26849. this.morphTargetManagers.forEach(function (o) {
  26850. _this.scene.addMorphTargetManager(o);
  26851. });
  26852. this.geometries.forEach(function (o) {
  26853. _this.scene.addGeometry(o);
  26854. });
  26855. this.transformNodes.forEach(function (o) {
  26856. _this.scene.addTransformNode(o);
  26857. });
  26858. this.lensFlareSystems.forEach(function (o) {
  26859. _this.scene.addLensFlareSystem(o);
  26860. });
  26861. this.actionManagers.forEach(function (o) {
  26862. _this.scene.addActionManager(o);
  26863. });
  26864. this.sounds.forEach(function (o) {
  26865. o.play();
  26866. o.autoplay = true;
  26867. _this.scene.mainSoundTrack.AddSound(o);
  26868. });
  26869. this.textures.forEach(function (o) {
  26870. _this.scene.addTexture;
  26871. });
  26872. };
  26873. /**
  26874. * Removes all the assets in the container from the scene
  26875. */
  26876. AssetContainer.prototype.removeAllFromScene = function () {
  26877. var _this = this;
  26878. this.cameras.forEach(function (o) {
  26879. _this.scene.removeCamera(o);
  26880. });
  26881. this.lights.forEach(function (o) {
  26882. _this.scene.removeLight(o);
  26883. });
  26884. this.meshes.forEach(function (o) {
  26885. _this.scene.removeMesh(o);
  26886. });
  26887. this.skeletons.forEach(function (o) {
  26888. _this.scene.removeSkeleton(o);
  26889. });
  26890. this.particleSystems.forEach(function (o) {
  26891. _this.scene.removeParticleSystem(o);
  26892. });
  26893. this.animations.forEach(function (o) {
  26894. _this.scene.removeAnimation(o);
  26895. });
  26896. this.animationGroups.forEach(function (o) {
  26897. _this.scene.removeAnimationGroup(o);
  26898. });
  26899. this.multiMaterials.forEach(function (o) {
  26900. _this.scene.removeMultiMaterial(o);
  26901. });
  26902. this.materials.forEach(function (o) {
  26903. _this.scene.removeMaterial(o);
  26904. });
  26905. this.morphTargetManagers.forEach(function (o) {
  26906. _this.scene.removeMorphTargetManager(o);
  26907. });
  26908. this.geometries.forEach(function (o) {
  26909. _this.scene.removeGeometry(o);
  26910. });
  26911. this.transformNodes.forEach(function (o) {
  26912. _this.scene.removeTransformNode(o);
  26913. });
  26914. this.lensFlareSystems.forEach(function (o) {
  26915. _this.scene.removeLensFlareSystem(o);
  26916. });
  26917. this.actionManagers.forEach(function (o) {
  26918. _this.scene.removeActionManager(o);
  26919. });
  26920. this.sounds.forEach(function (o) {
  26921. o.stop();
  26922. o.autoplay = false;
  26923. _this.scene.mainSoundTrack.RemoveSound(o);
  26924. });
  26925. this.textures.forEach(function (o) {
  26926. _this.scene.removeTexture(o);
  26927. });
  26928. };
  26929. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26930. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26931. var asset = sourceAssets_1[_i];
  26932. var move = true;
  26933. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26934. var keepAsset = keepAssets_1[_a];
  26935. if (asset === keepAsset) {
  26936. move = false;
  26937. break;
  26938. }
  26939. }
  26940. if (move) {
  26941. targetAssets.push(asset);
  26942. }
  26943. }
  26944. };
  26945. /**
  26946. * Removes all the assets contained in the scene and adds them to the container.
  26947. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26948. */
  26949. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26950. if (keepAssets === undefined) {
  26951. keepAssets = new KeepAssets();
  26952. }
  26953. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26954. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26955. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26956. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26957. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26958. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26959. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  26960. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26961. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26962. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26963. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26964. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26965. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26966. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26967. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26968. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  26969. this.removeAllFromScene();
  26970. };
  26971. return AssetContainer;
  26972. }());
  26973. BABYLON.AssetContainer = AssetContainer;
  26974. })(BABYLON || (BABYLON = {}));
  26975. //# sourceMappingURL=babylon.assetContainer.js.map
  26976. "use strict";
  26977. var BABYLON;
  26978. (function (BABYLON) {
  26979. var Buffer = /** @class */ (function () {
  26980. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26981. if (instanced === void 0) { instanced = false; }
  26982. if (engine instanceof BABYLON.Mesh) {
  26983. this._engine = engine.getScene().getEngine();
  26984. }
  26985. else {
  26986. this._engine = engine;
  26987. }
  26988. this._updatable = updatable;
  26989. this._instanced = instanced;
  26990. this._data = data;
  26991. this._strideSize = stride;
  26992. if (!postponeInternalCreation) {
  26993. this.create();
  26994. }
  26995. }
  26996. /**
  26997. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26998. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26999. * @param offset defines offset in the buffer (0 by default)
  27000. * @param size defines the size in floats of attributes (position is 3 for instance)
  27001. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  27002. * @param instanced defines if the vertex buffer contains indexed data
  27003. * @returns the new vertex buffer
  27004. */
  27005. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  27006. // a lot of these parameters are ignored as they are overriden by the buffer
  27007. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  27008. };
  27009. // Properties
  27010. Buffer.prototype.isUpdatable = function () {
  27011. return this._updatable;
  27012. };
  27013. Buffer.prototype.getData = function () {
  27014. return this._data;
  27015. };
  27016. Buffer.prototype.getBuffer = function () {
  27017. return this._buffer;
  27018. };
  27019. Buffer.prototype.getStrideSize = function () {
  27020. return this._strideSize;
  27021. };
  27022. // public getIsInstanced(): boolean {
  27023. // return this._instanced;
  27024. // }
  27025. // public get instanceDivisor(): number {
  27026. // return this._instanceDivisor;
  27027. // }
  27028. // public set instanceDivisor(value: number) {
  27029. // this._instanceDivisor = value;
  27030. // if (value == 0) {
  27031. // this._instanced = false;
  27032. // } else {
  27033. // this._instanced = true;
  27034. // }
  27035. // }
  27036. // Methods
  27037. Buffer.prototype.create = function (data) {
  27038. if (data === void 0) { data = null; }
  27039. if (!data && this._buffer) {
  27040. return; // nothing to do
  27041. }
  27042. data = data || this._data;
  27043. if (!data) {
  27044. return;
  27045. }
  27046. if (!this._buffer) {
  27047. if (this._updatable) {
  27048. this._buffer = this._engine.createDynamicVertexBuffer(data);
  27049. this._data = data;
  27050. }
  27051. else {
  27052. this._buffer = this._engine.createVertexBuffer(data);
  27053. }
  27054. }
  27055. else if (this._updatable) {
  27056. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  27057. this._data = data;
  27058. }
  27059. };
  27060. Buffer.prototype._rebuild = function () {
  27061. this._buffer = null;
  27062. this.create(this._data);
  27063. };
  27064. Buffer.prototype.update = function (data) {
  27065. this.create(data);
  27066. };
  27067. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  27068. if (!this._buffer) {
  27069. return;
  27070. }
  27071. if (this._updatable) {
  27072. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  27073. this._data = null;
  27074. }
  27075. };
  27076. Buffer.prototype.dispose = function () {
  27077. if (!this._buffer) {
  27078. return;
  27079. }
  27080. if (this._engine._releaseBuffer(this._buffer)) {
  27081. this._buffer = null;
  27082. }
  27083. };
  27084. return Buffer;
  27085. }());
  27086. BABYLON.Buffer = Buffer;
  27087. })(BABYLON || (BABYLON = {}));
  27088. //# sourceMappingURL=babylon.buffer.js.map
  27089. "use strict";
  27090. var BABYLON;
  27091. (function (BABYLON) {
  27092. var VertexBuffer = /** @class */ (function () {
  27093. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  27094. if (data instanceof BABYLON.Buffer) {
  27095. if (!stride) {
  27096. stride = data.getStrideSize();
  27097. }
  27098. this._buffer = data;
  27099. this._ownsBuffer = false;
  27100. }
  27101. else {
  27102. if (!stride) {
  27103. stride = VertexBuffer.DeduceStride(kind);
  27104. }
  27105. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  27106. this._ownsBuffer = true;
  27107. }
  27108. this._stride = stride;
  27109. this._instanced = instanced !== undefined ? instanced : false;
  27110. this._instanceDivisor = instanced ? 1 : 0;
  27111. this._offset = offset ? offset : 0;
  27112. this._size = size ? size : stride;
  27113. this._kind = kind;
  27114. }
  27115. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  27116. /**
  27117. * Gets or sets the instance divisor when in instanced mode
  27118. */
  27119. get: function () {
  27120. return this._instanceDivisor;
  27121. },
  27122. set: function (value) {
  27123. this._instanceDivisor = value;
  27124. if (value == 0) {
  27125. this._instanced = false;
  27126. }
  27127. else {
  27128. this._instanced = true;
  27129. }
  27130. },
  27131. enumerable: true,
  27132. configurable: true
  27133. });
  27134. VertexBuffer.prototype._rebuild = function () {
  27135. if (!this._buffer) {
  27136. return;
  27137. }
  27138. this._buffer._rebuild();
  27139. };
  27140. /**
  27141. * Returns the kind of the VertexBuffer (string).
  27142. */
  27143. VertexBuffer.prototype.getKind = function () {
  27144. return this._kind;
  27145. };
  27146. // Properties
  27147. /**
  27148. * Boolean : is the VertexBuffer updatable ?
  27149. */
  27150. VertexBuffer.prototype.isUpdatable = function () {
  27151. return this._buffer.isUpdatable();
  27152. };
  27153. /**
  27154. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  27155. */
  27156. VertexBuffer.prototype.getData = function () {
  27157. return this._buffer.getData();
  27158. };
  27159. /**
  27160. * Returns the WebGLBuffer associated to the VertexBuffer.
  27161. */
  27162. VertexBuffer.prototype.getBuffer = function () {
  27163. return this._buffer.getBuffer();
  27164. };
  27165. /**
  27166. * Returns the stride of the VertexBuffer (integer).
  27167. */
  27168. VertexBuffer.prototype.getStrideSize = function () {
  27169. return this._stride;
  27170. };
  27171. /**
  27172. * Returns the offset (integer).
  27173. */
  27174. VertexBuffer.prototype.getOffset = function () {
  27175. return this._offset;
  27176. };
  27177. /**
  27178. * Returns the VertexBuffer total size (integer).
  27179. */
  27180. VertexBuffer.prototype.getSize = function () {
  27181. return this._size;
  27182. };
  27183. /**
  27184. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  27185. */
  27186. VertexBuffer.prototype.getIsInstanced = function () {
  27187. return this._instanced;
  27188. };
  27189. /**
  27190. * Returns the instancing divisor, zero for non-instanced (integer).
  27191. */
  27192. VertexBuffer.prototype.getInstanceDivisor = function () {
  27193. return this._instanceDivisor;
  27194. };
  27195. // Methods
  27196. /**
  27197. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  27198. * Returns the created WebGLBuffer.
  27199. */
  27200. VertexBuffer.prototype.create = function (data) {
  27201. return this._buffer.create(data);
  27202. };
  27203. /**
  27204. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  27205. * This function will create a new buffer if the current one is not updatable
  27206. * Returns the updated WebGLBuffer.
  27207. */
  27208. VertexBuffer.prototype.update = function (data) {
  27209. return this._buffer.update(data);
  27210. };
  27211. /**
  27212. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  27213. * Returns the directly updated WebGLBuffer.
  27214. */
  27215. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  27216. return this._buffer.updateDirectly(data, offset);
  27217. };
  27218. /**
  27219. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  27220. */
  27221. VertexBuffer.prototype.dispose = function () {
  27222. if (this._ownsBuffer) {
  27223. this._buffer.dispose();
  27224. }
  27225. };
  27226. Object.defineProperty(VertexBuffer, "PositionKind", {
  27227. get: function () {
  27228. return VertexBuffer._PositionKind;
  27229. },
  27230. enumerable: true,
  27231. configurable: true
  27232. });
  27233. Object.defineProperty(VertexBuffer, "NormalKind", {
  27234. get: function () {
  27235. return VertexBuffer._NormalKind;
  27236. },
  27237. enumerable: true,
  27238. configurable: true
  27239. });
  27240. Object.defineProperty(VertexBuffer, "TangentKind", {
  27241. get: function () {
  27242. return VertexBuffer._TangentKind;
  27243. },
  27244. enumerable: true,
  27245. configurable: true
  27246. });
  27247. Object.defineProperty(VertexBuffer, "UVKind", {
  27248. get: function () {
  27249. return VertexBuffer._UVKind;
  27250. },
  27251. enumerable: true,
  27252. configurable: true
  27253. });
  27254. Object.defineProperty(VertexBuffer, "UV2Kind", {
  27255. get: function () {
  27256. return VertexBuffer._UV2Kind;
  27257. },
  27258. enumerable: true,
  27259. configurable: true
  27260. });
  27261. Object.defineProperty(VertexBuffer, "UV3Kind", {
  27262. get: function () {
  27263. return VertexBuffer._UV3Kind;
  27264. },
  27265. enumerable: true,
  27266. configurable: true
  27267. });
  27268. Object.defineProperty(VertexBuffer, "UV4Kind", {
  27269. get: function () {
  27270. return VertexBuffer._UV4Kind;
  27271. },
  27272. enumerable: true,
  27273. configurable: true
  27274. });
  27275. Object.defineProperty(VertexBuffer, "UV5Kind", {
  27276. get: function () {
  27277. return VertexBuffer._UV5Kind;
  27278. },
  27279. enumerable: true,
  27280. configurable: true
  27281. });
  27282. Object.defineProperty(VertexBuffer, "UV6Kind", {
  27283. get: function () {
  27284. return VertexBuffer._UV6Kind;
  27285. },
  27286. enumerable: true,
  27287. configurable: true
  27288. });
  27289. Object.defineProperty(VertexBuffer, "ColorKind", {
  27290. get: function () {
  27291. return VertexBuffer._ColorKind;
  27292. },
  27293. enumerable: true,
  27294. configurable: true
  27295. });
  27296. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  27297. get: function () {
  27298. return VertexBuffer._MatricesIndicesKind;
  27299. },
  27300. enumerable: true,
  27301. configurable: true
  27302. });
  27303. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  27304. get: function () {
  27305. return VertexBuffer._MatricesWeightsKind;
  27306. },
  27307. enumerable: true,
  27308. configurable: true
  27309. });
  27310. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  27311. get: function () {
  27312. return VertexBuffer._MatricesIndicesExtraKind;
  27313. },
  27314. enumerable: true,
  27315. configurable: true
  27316. });
  27317. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  27318. get: function () {
  27319. return VertexBuffer._MatricesWeightsExtraKind;
  27320. },
  27321. enumerable: true,
  27322. configurable: true
  27323. });
  27324. /**
  27325. * Deduces the stride given a kind.
  27326. * @param kind The kind string to deduce
  27327. * @returns The deduced stride
  27328. */
  27329. VertexBuffer.DeduceStride = function (kind) {
  27330. switch (kind) {
  27331. case VertexBuffer.UVKind:
  27332. case VertexBuffer.UV2Kind:
  27333. case VertexBuffer.UV3Kind:
  27334. case VertexBuffer.UV4Kind:
  27335. case VertexBuffer.UV5Kind:
  27336. case VertexBuffer.UV6Kind:
  27337. return 2;
  27338. case VertexBuffer.NormalKind:
  27339. case VertexBuffer.PositionKind:
  27340. return 3;
  27341. case VertexBuffer.ColorKind:
  27342. case VertexBuffer.MatricesIndicesKind:
  27343. case VertexBuffer.MatricesIndicesExtraKind:
  27344. case VertexBuffer.MatricesWeightsKind:
  27345. case VertexBuffer.MatricesWeightsExtraKind:
  27346. case VertexBuffer.TangentKind:
  27347. return 4;
  27348. default:
  27349. throw new Error("Invalid kind '" + kind + "'");
  27350. }
  27351. };
  27352. // Enums
  27353. VertexBuffer._PositionKind = "position";
  27354. VertexBuffer._NormalKind = "normal";
  27355. VertexBuffer._TangentKind = "tangent";
  27356. VertexBuffer._UVKind = "uv";
  27357. VertexBuffer._UV2Kind = "uv2";
  27358. VertexBuffer._UV3Kind = "uv3";
  27359. VertexBuffer._UV4Kind = "uv4";
  27360. VertexBuffer._UV5Kind = "uv5";
  27361. VertexBuffer._UV6Kind = "uv6";
  27362. VertexBuffer._ColorKind = "color";
  27363. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  27364. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  27365. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  27366. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  27367. return VertexBuffer;
  27368. }());
  27369. BABYLON.VertexBuffer = VertexBuffer;
  27370. })(BABYLON || (BABYLON = {}));
  27371. //# sourceMappingURL=babylon.vertexBuffer.js.map
  27372. "use strict";
  27373. var BABYLON;
  27374. (function (BABYLON) {
  27375. /**
  27376. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  27377. */
  27378. var DummyInternalTextureTracker = /** @class */ (function () {
  27379. function DummyInternalTextureTracker() {
  27380. /**
  27381. * Gets or set the previous tracker in the list
  27382. */
  27383. this.previous = null;
  27384. /**
  27385. * Gets or set the next tracker in the list
  27386. */
  27387. this.next = null;
  27388. }
  27389. return DummyInternalTextureTracker;
  27390. }());
  27391. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  27392. })(BABYLON || (BABYLON = {}));
  27393. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  27394. "use strict";
  27395. var BABYLON;
  27396. (function (BABYLON) {
  27397. /**
  27398. * Class used to store data associated with WebGL texture data for the engine
  27399. * This class should not be used directly
  27400. */
  27401. var InternalTexture = /** @class */ (function () {
  27402. /**
  27403. * Creates a new InternalTexture
  27404. * @param engine defines the engine to use
  27405. * @param dataSource defines the type of data that will be used
  27406. */
  27407. function InternalTexture(engine, dataSource) {
  27408. /**
  27409. * Observable called when the texture is loaded
  27410. */
  27411. this.onLoadedObservable = new BABYLON.Observable();
  27412. /**
  27413. * Gets or set the previous tracker in the list
  27414. */
  27415. this.previous = null;
  27416. /**
  27417. * Gets or set the next tracker in the list
  27418. */
  27419. this.next = null;
  27420. // Private
  27421. /** @ignore */
  27422. this._initialSlot = -1;
  27423. /** @ignore */
  27424. this._designatedSlot = -1;
  27425. /** @ignore */
  27426. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  27427. /** @ignore */
  27428. this._comparisonFunction = 0;
  27429. /** @ignore */
  27430. this._references = 1;
  27431. this._engine = engine;
  27432. this._dataSource = dataSource;
  27433. this._webGLTexture = engine._createTexture();
  27434. }
  27435. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  27436. /**
  27437. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  27438. */
  27439. get: function () {
  27440. return this._dataSource;
  27441. },
  27442. enumerable: true,
  27443. configurable: true
  27444. });
  27445. /**
  27446. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  27447. */
  27448. InternalTexture.prototype.incrementReferences = function () {
  27449. this._references++;
  27450. };
  27451. /**
  27452. * Change the size of the texture (not the size of the content)
  27453. * @param width defines the new width
  27454. * @param height defines the new height
  27455. * @param depth defines the new depth (1 by default)
  27456. */
  27457. InternalTexture.prototype.updateSize = function (width, height, depth) {
  27458. if (depth === void 0) { depth = 1; }
  27459. this.width = width;
  27460. this.height = height;
  27461. this.depth = depth;
  27462. this.baseWidth = width;
  27463. this.baseHeight = height;
  27464. this.baseDepth = depth;
  27465. this._size = width * height * depth;
  27466. };
  27467. /** @ignore */
  27468. InternalTexture.prototype._rebuild = function () {
  27469. var _this = this;
  27470. var proxy;
  27471. this.isReady = false;
  27472. this._cachedCoordinatesMode = null;
  27473. this._cachedWrapU = null;
  27474. this._cachedWrapV = null;
  27475. this._cachedAnisotropicFilteringLevel = null;
  27476. switch (this._dataSource) {
  27477. case InternalTexture.DATASOURCE_TEMP:
  27478. return;
  27479. case InternalTexture.DATASOURCE_URL:
  27480. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  27481. _this.isReady = true;
  27482. }, null, this._buffer, undefined, this.format);
  27483. proxy._swapAndDie(this);
  27484. return;
  27485. case InternalTexture.DATASOURCE_RAW:
  27486. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  27487. proxy._swapAndDie(this);
  27488. this.isReady = true;
  27489. return;
  27490. case InternalTexture.DATASOURCE_RAW3D:
  27491. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  27492. proxy._swapAndDie(this);
  27493. this.isReady = true;
  27494. return;
  27495. case InternalTexture.DATASOURCE_DYNAMIC:
  27496. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  27497. proxy._swapAndDie(this);
  27498. // The engine will make sure to update content so no need to flag it as isReady = true
  27499. return;
  27500. case InternalTexture.DATASOURCE_RENDERTARGET:
  27501. var options = new BABYLON.RenderTargetCreationOptions();
  27502. options.generateDepthBuffer = this._generateDepthBuffer;
  27503. options.generateMipMaps = this.generateMipMaps;
  27504. options.generateStencilBuffer = this._generateStencilBuffer;
  27505. options.samplingMode = this.samplingMode;
  27506. options.type = this.type;
  27507. if (this.isCube) {
  27508. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  27509. }
  27510. else {
  27511. var size = {
  27512. width: this.width,
  27513. height: this.height
  27514. };
  27515. proxy = this._engine.createRenderTargetTexture(size, options);
  27516. }
  27517. proxy._swapAndDie(this);
  27518. this.isReady = true;
  27519. return;
  27520. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  27521. var depthTextureOptions = {
  27522. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  27523. comparisonFunction: this._comparisonFunction,
  27524. generateStencil: this._generateStencilBuffer,
  27525. isCube: this.isCube
  27526. };
  27527. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  27528. proxy._swapAndDie(this);
  27529. this.isReady = true;
  27530. return;
  27531. case InternalTexture.DATASOURCE_CUBE:
  27532. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  27533. _this.isReady = true;
  27534. }, null, this.format, this._extension);
  27535. proxy._swapAndDie(this);
  27536. return;
  27537. case InternalTexture.DATASOURCE_CUBERAW:
  27538. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  27539. proxy._swapAndDie(this);
  27540. this.isReady = true;
  27541. return;
  27542. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  27543. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  27544. if (proxy) {
  27545. proxy._swapAndDie(_this);
  27546. }
  27547. _this.isReady = true;
  27548. }, null, this.format, this._extension);
  27549. return;
  27550. }
  27551. };
  27552. InternalTexture.prototype._swapAndDie = function (target) {
  27553. target._webGLTexture = this._webGLTexture;
  27554. if (this._framebuffer) {
  27555. target._framebuffer = this._framebuffer;
  27556. }
  27557. if (this._depthStencilBuffer) {
  27558. target._depthStencilBuffer = this._depthStencilBuffer;
  27559. }
  27560. if (this._lodTextureHigh) {
  27561. if (target._lodTextureHigh) {
  27562. target._lodTextureHigh.dispose();
  27563. }
  27564. target._lodTextureHigh = this._lodTextureHigh;
  27565. }
  27566. if (this._lodTextureMid) {
  27567. if (target._lodTextureMid) {
  27568. target._lodTextureMid.dispose();
  27569. }
  27570. target._lodTextureMid = this._lodTextureMid;
  27571. }
  27572. if (this._lodTextureLow) {
  27573. if (target._lodTextureLow) {
  27574. target._lodTextureLow.dispose();
  27575. }
  27576. target._lodTextureLow = this._lodTextureLow;
  27577. }
  27578. var cache = this._engine.getLoadedTexturesCache();
  27579. var index = cache.indexOf(this);
  27580. if (index !== -1) {
  27581. cache.splice(index, 1);
  27582. }
  27583. };
  27584. /**
  27585. * Dispose the current allocated resources
  27586. */
  27587. InternalTexture.prototype.dispose = function () {
  27588. if (!this._webGLTexture) {
  27589. return;
  27590. }
  27591. this._references--;
  27592. if (this._references === 0) {
  27593. this._engine._releaseTexture(this);
  27594. this._webGLTexture = null;
  27595. this.previous = null;
  27596. this.next = null;
  27597. }
  27598. };
  27599. /**
  27600. * The source of the texture data is unknown
  27601. */
  27602. InternalTexture.DATASOURCE_UNKNOWN = 0;
  27603. /**
  27604. * Texture data comes from an URL
  27605. */
  27606. InternalTexture.DATASOURCE_URL = 1;
  27607. /**
  27608. * Texture data is only used for temporary storage
  27609. */
  27610. InternalTexture.DATASOURCE_TEMP = 2;
  27611. /**
  27612. * Texture data comes from raw data (ArrayBuffer)
  27613. */
  27614. InternalTexture.DATASOURCE_RAW = 3;
  27615. /**
  27616. * Texture content is dynamic (video or dynamic texture)
  27617. */
  27618. InternalTexture.DATASOURCE_DYNAMIC = 4;
  27619. /**
  27620. * Texture content is generated by rendering to it
  27621. */
  27622. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  27623. /**
  27624. * Texture content is part of a multi render target process
  27625. */
  27626. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  27627. /**
  27628. * Texture data comes from a cube data file
  27629. */
  27630. InternalTexture.DATASOURCE_CUBE = 7;
  27631. /**
  27632. * Texture data comes from a raw cube data
  27633. */
  27634. InternalTexture.DATASOURCE_CUBERAW = 8;
  27635. /**
  27636. * Texture data come from a prefiltered cube data file
  27637. */
  27638. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  27639. /**
  27640. * Texture content is raw 3D data
  27641. */
  27642. InternalTexture.DATASOURCE_RAW3D = 10;
  27643. /**
  27644. * Texture content is a depth texture
  27645. */
  27646. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  27647. return InternalTexture;
  27648. }());
  27649. BABYLON.InternalTexture = InternalTexture;
  27650. })(BABYLON || (BABYLON = {}));
  27651. //# sourceMappingURL=babylon.internalTexture.js.map
  27652. "use strict";
  27653. var BABYLON;
  27654. (function (BABYLON) {
  27655. var BaseTexture = /** @class */ (function () {
  27656. function BaseTexture(scene) {
  27657. this._hasAlpha = false;
  27658. this.getAlphaFromRGB = false;
  27659. this.level = 1;
  27660. this.coordinatesIndex = 0;
  27661. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  27662. /**
  27663. * | Value | Type | Description |
  27664. * | ----- | ------------------ | ----------- |
  27665. * | 0 | CLAMP_ADDRESSMODE | |
  27666. * | 1 | WRAP_ADDRESSMODE | |
  27667. * | 2 | MIRROR_ADDRESSMODE | |
  27668. */
  27669. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27670. /**
  27671. * | Value | Type | Description |
  27672. * | ----- | ------------------ | ----------- |
  27673. * | 0 | CLAMP_ADDRESSMODE | |
  27674. * | 1 | WRAP_ADDRESSMODE | |
  27675. * | 2 | MIRROR_ADDRESSMODE | |
  27676. */
  27677. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27678. /**
  27679. * | Value | Type | Description |
  27680. * | ----- | ------------------ | ----------- |
  27681. * | 0 | CLAMP_ADDRESSMODE | |
  27682. * | 1 | WRAP_ADDRESSMODE | |
  27683. * | 2 | MIRROR_ADDRESSMODE | |
  27684. */
  27685. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  27686. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  27687. this.isCube = false;
  27688. this.is3D = false;
  27689. this.gammaSpace = true;
  27690. this.invertZ = false;
  27691. this.lodLevelInAlpha = false;
  27692. this.lodGenerationOffset = 0.0;
  27693. this.lodGenerationScale = 0.8;
  27694. this.isRenderTarget = false;
  27695. this.animations = new Array();
  27696. /**
  27697. * An event triggered when the texture is disposed.
  27698. */
  27699. this.onDisposeObservable = new BABYLON.Observable();
  27700. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27701. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27702. if (this._scene) {
  27703. this._scene.textures.push(this);
  27704. }
  27705. this._uid = null;
  27706. }
  27707. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  27708. get: function () {
  27709. return this._hasAlpha;
  27710. },
  27711. set: function (value) {
  27712. if (this._hasAlpha === value) {
  27713. return;
  27714. }
  27715. this._hasAlpha = value;
  27716. if (this._scene) {
  27717. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  27718. }
  27719. },
  27720. enumerable: true,
  27721. configurable: true
  27722. });
  27723. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  27724. get: function () {
  27725. return this._coordinatesMode;
  27726. },
  27727. /**
  27728. * How a texture is mapped.
  27729. *
  27730. * | Value | Type | Description |
  27731. * | ----- | ----------------------------------- | ----------- |
  27732. * | 0 | EXPLICIT_MODE | |
  27733. * | 1 | SPHERICAL_MODE | |
  27734. * | 2 | PLANAR_MODE | |
  27735. * | 3 | CUBIC_MODE | |
  27736. * | 4 | PROJECTION_MODE | |
  27737. * | 5 | SKYBOX_MODE | |
  27738. * | 6 | INVCUBIC_MODE | |
  27739. * | 7 | EQUIRECTANGULAR_MODE | |
  27740. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  27741. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  27742. */
  27743. set: function (value) {
  27744. if (this._coordinatesMode === value) {
  27745. return;
  27746. }
  27747. this._coordinatesMode = value;
  27748. if (this._scene) {
  27749. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27750. }
  27751. },
  27752. enumerable: true,
  27753. configurable: true
  27754. });
  27755. Object.defineProperty(BaseTexture.prototype, "uid", {
  27756. get: function () {
  27757. if (!this._uid) {
  27758. this._uid = BABYLON.Tools.RandomId();
  27759. }
  27760. return this._uid;
  27761. },
  27762. enumerable: true,
  27763. configurable: true
  27764. });
  27765. BaseTexture.prototype.toString = function () {
  27766. return this.name;
  27767. };
  27768. BaseTexture.prototype.getClassName = function () {
  27769. return "BaseTexture";
  27770. };
  27771. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  27772. set: function (callback) {
  27773. if (this._onDisposeObserver) {
  27774. this.onDisposeObservable.remove(this._onDisposeObserver);
  27775. }
  27776. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27777. },
  27778. enumerable: true,
  27779. configurable: true
  27780. });
  27781. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  27782. get: function () {
  27783. return true;
  27784. },
  27785. enumerable: true,
  27786. configurable: true
  27787. });
  27788. BaseTexture.prototype.getScene = function () {
  27789. return this._scene;
  27790. };
  27791. BaseTexture.prototype.getTextureMatrix = function () {
  27792. return BABYLON.Matrix.IdentityReadOnly;
  27793. };
  27794. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27795. return BABYLON.Matrix.IdentityReadOnly;
  27796. };
  27797. BaseTexture.prototype.getInternalTexture = function () {
  27798. return this._texture;
  27799. };
  27800. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27801. return !this.isBlocking || this.isReady();
  27802. };
  27803. BaseTexture.prototype.isReady = function () {
  27804. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27805. this.delayLoad();
  27806. return false;
  27807. }
  27808. if (this._texture) {
  27809. return this._texture.isReady;
  27810. }
  27811. return false;
  27812. };
  27813. BaseTexture.prototype.getSize = function () {
  27814. if (this._texture && this._texture.width) {
  27815. return new BABYLON.Size(this._texture.width, this._texture.height);
  27816. }
  27817. if (this._texture && this._texture._size) {
  27818. return new BABYLON.Size(this._texture._size, this._texture._size);
  27819. }
  27820. return BABYLON.Size.Zero();
  27821. };
  27822. BaseTexture.prototype.getBaseSize = function () {
  27823. if (!this.isReady() || !this._texture)
  27824. return BABYLON.Size.Zero();
  27825. if (this._texture._size) {
  27826. return new BABYLON.Size(this._texture._size, this._texture._size);
  27827. }
  27828. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27829. };
  27830. BaseTexture.prototype.scale = function (ratio) {
  27831. };
  27832. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27833. get: function () {
  27834. return false;
  27835. },
  27836. enumerable: true,
  27837. configurable: true
  27838. });
  27839. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27840. if (!this._scene) {
  27841. return null;
  27842. }
  27843. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27844. for (var index = 0; index < texturesCache.length; index++) {
  27845. var texturesCacheEntry = texturesCache[index];
  27846. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27847. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27848. texturesCacheEntry.incrementReferences();
  27849. return texturesCacheEntry;
  27850. }
  27851. }
  27852. }
  27853. return null;
  27854. };
  27855. BaseTexture.prototype._rebuild = function () {
  27856. };
  27857. BaseTexture.prototype.delayLoad = function () {
  27858. };
  27859. BaseTexture.prototype.clone = function () {
  27860. return null;
  27861. };
  27862. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27863. get: function () {
  27864. if (!this._texture) {
  27865. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27866. }
  27867. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27868. },
  27869. enumerable: true,
  27870. configurable: true
  27871. });
  27872. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27873. get: function () {
  27874. if (!this._texture) {
  27875. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27876. }
  27877. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27878. },
  27879. enumerable: true,
  27880. configurable: true
  27881. });
  27882. BaseTexture.prototype.readPixels = function (faceIndex) {
  27883. if (faceIndex === void 0) { faceIndex = 0; }
  27884. if (!this._texture) {
  27885. return null;
  27886. }
  27887. var size = this.getSize();
  27888. var scene = this.getScene();
  27889. if (!scene) {
  27890. return null;
  27891. }
  27892. var engine = scene.getEngine();
  27893. if (this._texture.isCube) {
  27894. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27895. }
  27896. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27897. };
  27898. BaseTexture.prototype.releaseInternalTexture = function () {
  27899. if (this._texture) {
  27900. this._texture.dispose();
  27901. this._texture = null;
  27902. }
  27903. };
  27904. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27905. get: function () {
  27906. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27907. return null;
  27908. }
  27909. if (!this._texture._sphericalPolynomial) {
  27910. this._texture._sphericalPolynomial =
  27911. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27912. }
  27913. return this._texture._sphericalPolynomial;
  27914. },
  27915. set: function (value) {
  27916. if (this._texture) {
  27917. this._texture._sphericalPolynomial = value;
  27918. }
  27919. },
  27920. enumerable: true,
  27921. configurable: true
  27922. });
  27923. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27924. get: function () {
  27925. if (this._texture) {
  27926. return this._texture._lodTextureHigh;
  27927. }
  27928. return null;
  27929. },
  27930. enumerable: true,
  27931. configurable: true
  27932. });
  27933. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27934. get: function () {
  27935. if (this._texture) {
  27936. return this._texture._lodTextureMid;
  27937. }
  27938. return null;
  27939. },
  27940. enumerable: true,
  27941. configurable: true
  27942. });
  27943. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27944. get: function () {
  27945. if (this._texture) {
  27946. return this._texture._lodTextureLow;
  27947. }
  27948. return null;
  27949. },
  27950. enumerable: true,
  27951. configurable: true
  27952. });
  27953. BaseTexture.prototype.dispose = function () {
  27954. if (!this._scene) {
  27955. return;
  27956. }
  27957. // Animations
  27958. this._scene.stopAnimation(this);
  27959. // Remove from scene
  27960. this._scene._removePendingData(this);
  27961. var index = this._scene.textures.indexOf(this);
  27962. if (index >= 0) {
  27963. this._scene.textures.splice(index, 1);
  27964. }
  27965. if (this._texture === undefined) {
  27966. return;
  27967. }
  27968. // Release
  27969. this.releaseInternalTexture();
  27970. // Callback
  27971. this.onDisposeObservable.notifyObservers(this);
  27972. this.onDisposeObservable.clear();
  27973. };
  27974. BaseTexture.prototype.serialize = function () {
  27975. if (!this.name) {
  27976. return null;
  27977. }
  27978. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27979. // Animations
  27980. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27981. return serializationObject;
  27982. };
  27983. BaseTexture.WhenAllReady = function (textures, callback) {
  27984. var numRemaining = textures.length;
  27985. if (numRemaining === 0) {
  27986. callback();
  27987. return;
  27988. }
  27989. var _loop_1 = function () {
  27990. texture = textures[i];
  27991. if (texture.isReady()) {
  27992. if (--numRemaining === 0) {
  27993. callback();
  27994. }
  27995. }
  27996. else {
  27997. onLoadObservable = texture.onLoadObservable;
  27998. var onLoadCallback_1 = function () {
  27999. onLoadObservable.removeCallback(onLoadCallback_1);
  28000. if (--numRemaining === 0) {
  28001. callback();
  28002. }
  28003. };
  28004. onLoadObservable.add(onLoadCallback_1);
  28005. }
  28006. };
  28007. var texture, onLoadObservable;
  28008. for (var i = 0; i < textures.length; i++) {
  28009. _loop_1();
  28010. }
  28011. };
  28012. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  28013. __decorate([
  28014. BABYLON.serialize()
  28015. ], BaseTexture.prototype, "name", void 0);
  28016. __decorate([
  28017. BABYLON.serialize("hasAlpha")
  28018. ], BaseTexture.prototype, "_hasAlpha", void 0);
  28019. __decorate([
  28020. BABYLON.serialize()
  28021. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  28022. __decorate([
  28023. BABYLON.serialize()
  28024. ], BaseTexture.prototype, "level", void 0);
  28025. __decorate([
  28026. BABYLON.serialize()
  28027. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  28028. __decorate([
  28029. BABYLON.serialize("coordinatesMode")
  28030. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  28031. __decorate([
  28032. BABYLON.serialize()
  28033. ], BaseTexture.prototype, "wrapU", void 0);
  28034. __decorate([
  28035. BABYLON.serialize()
  28036. ], BaseTexture.prototype, "wrapV", void 0);
  28037. __decorate([
  28038. BABYLON.serialize()
  28039. ], BaseTexture.prototype, "wrapR", void 0);
  28040. __decorate([
  28041. BABYLON.serialize()
  28042. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  28043. __decorate([
  28044. BABYLON.serialize()
  28045. ], BaseTexture.prototype, "isCube", void 0);
  28046. __decorate([
  28047. BABYLON.serialize()
  28048. ], BaseTexture.prototype, "is3D", void 0);
  28049. __decorate([
  28050. BABYLON.serialize()
  28051. ], BaseTexture.prototype, "gammaSpace", void 0);
  28052. __decorate([
  28053. BABYLON.serialize()
  28054. ], BaseTexture.prototype, "invertZ", void 0);
  28055. __decorate([
  28056. BABYLON.serialize()
  28057. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  28058. __decorate([
  28059. BABYLON.serialize()
  28060. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  28061. __decorate([
  28062. BABYLON.serialize()
  28063. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  28064. __decorate([
  28065. BABYLON.serialize()
  28066. ], BaseTexture.prototype, "isRenderTarget", void 0);
  28067. return BaseTexture;
  28068. }());
  28069. BABYLON.BaseTexture = BaseTexture;
  28070. })(BABYLON || (BABYLON = {}));
  28071. //# sourceMappingURL=babylon.baseTexture.js.map
  28072. "use strict";
  28073. var BABYLON;
  28074. (function (BABYLON) {
  28075. var Texture = /** @class */ (function (_super) {
  28076. __extends(Texture, _super);
  28077. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  28078. if (noMipmap === void 0) { noMipmap = false; }
  28079. if (invertY === void 0) { invertY = true; }
  28080. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28081. if (onLoad === void 0) { onLoad = null; }
  28082. if (onError === void 0) { onError = null; }
  28083. if (buffer === void 0) { buffer = null; }
  28084. if (deleteBuffer === void 0) { deleteBuffer = false; }
  28085. var _this = _super.call(this, scene) || this;
  28086. _this.uOffset = 0;
  28087. _this.vOffset = 0;
  28088. _this.uScale = 1.0;
  28089. _this.vScale = 1.0;
  28090. _this.uAng = 0;
  28091. _this.vAng = 0;
  28092. _this.wAng = 0;
  28093. _this._isBlocking = true;
  28094. _this.name = url || "";
  28095. _this.url = url;
  28096. _this._noMipmap = noMipmap;
  28097. _this._invertY = invertY;
  28098. _this._samplingMode = samplingMode;
  28099. _this._buffer = buffer;
  28100. _this._deleteBuffer = deleteBuffer;
  28101. if (format) {
  28102. _this._format = format;
  28103. }
  28104. scene = _this.getScene();
  28105. if (!scene) {
  28106. return _this;
  28107. }
  28108. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  28109. var load = function () {
  28110. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  28111. _this.onLoadObservable.notifyObservers(_this);
  28112. }
  28113. if (onLoad) {
  28114. onLoad();
  28115. }
  28116. if (!_this.isBlocking && scene) {
  28117. scene.resetCachedMaterial();
  28118. }
  28119. };
  28120. if (!_this.url) {
  28121. _this._delayedOnLoad = load;
  28122. _this._delayedOnError = onError;
  28123. return _this;
  28124. }
  28125. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  28126. if (!_this._texture) {
  28127. if (!scene.useDelayedTextureLoading) {
  28128. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  28129. if (deleteBuffer) {
  28130. delete _this._buffer;
  28131. }
  28132. }
  28133. else {
  28134. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28135. _this._delayedOnLoad = load;
  28136. _this._delayedOnError = onError;
  28137. }
  28138. }
  28139. else {
  28140. if (_this._texture.isReady) {
  28141. BABYLON.Tools.SetImmediate(function () { return load(); });
  28142. }
  28143. else {
  28144. _this._texture.onLoadedObservable.add(load);
  28145. }
  28146. }
  28147. return _this;
  28148. }
  28149. Object.defineProperty(Texture.prototype, "noMipmap", {
  28150. get: function () {
  28151. return this._noMipmap;
  28152. },
  28153. enumerable: true,
  28154. configurable: true
  28155. });
  28156. Object.defineProperty(Texture.prototype, "isBlocking", {
  28157. get: function () {
  28158. return this._isBlocking;
  28159. },
  28160. set: function (value) {
  28161. this._isBlocking = value;
  28162. },
  28163. enumerable: true,
  28164. configurable: true
  28165. });
  28166. Object.defineProperty(Texture.prototype, "samplingMode", {
  28167. get: function () {
  28168. return this._samplingMode;
  28169. },
  28170. enumerable: true,
  28171. configurable: true
  28172. });
  28173. Texture.prototype.updateURL = function (url) {
  28174. this.url = url;
  28175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28176. this.delayLoad();
  28177. };
  28178. Texture.prototype.delayLoad = function () {
  28179. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28180. return;
  28181. }
  28182. var scene = this.getScene();
  28183. if (!scene) {
  28184. return;
  28185. }
  28186. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28187. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  28188. if (!this._texture) {
  28189. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  28190. if (this._deleteBuffer) {
  28191. delete this._buffer;
  28192. }
  28193. }
  28194. else {
  28195. if (this._delayedOnLoad) {
  28196. if (this._texture.isReady) {
  28197. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  28198. }
  28199. else {
  28200. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  28201. }
  28202. }
  28203. }
  28204. this._delayedOnLoad = null;
  28205. this._delayedOnError = null;
  28206. };
  28207. Texture.prototype.updateSamplingMode = function (samplingMode) {
  28208. if (!this._texture) {
  28209. return;
  28210. }
  28211. var scene = this.getScene();
  28212. if (!scene) {
  28213. return;
  28214. }
  28215. this._samplingMode = samplingMode;
  28216. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  28217. };
  28218. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  28219. x *= this.uScale;
  28220. y *= this.vScale;
  28221. x -= 0.5 * this.uScale;
  28222. y -= 0.5 * this.vScale;
  28223. z -= 0.5;
  28224. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  28225. t.x += 0.5 * this.uScale + this.uOffset;
  28226. t.y += 0.5 * this.vScale + this.vOffset;
  28227. t.z += 0.5;
  28228. };
  28229. Texture.prototype.getTextureMatrix = function () {
  28230. var _this = this;
  28231. if (this.uOffset === this._cachedUOffset &&
  28232. this.vOffset === this._cachedVOffset &&
  28233. this.uScale === this._cachedUScale &&
  28234. this.vScale === this._cachedVScale &&
  28235. this.uAng === this._cachedUAng &&
  28236. this.vAng === this._cachedVAng &&
  28237. this.wAng === this._cachedWAng) {
  28238. return this._cachedTextureMatrix;
  28239. }
  28240. this._cachedUOffset = this.uOffset;
  28241. this._cachedVOffset = this.vOffset;
  28242. this._cachedUScale = this.uScale;
  28243. this._cachedVScale = this.vScale;
  28244. this._cachedUAng = this.uAng;
  28245. this._cachedVAng = this.vAng;
  28246. this._cachedWAng = this.wAng;
  28247. if (!this._cachedTextureMatrix) {
  28248. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  28249. this._rowGenerationMatrix = new BABYLON.Matrix();
  28250. this._t0 = BABYLON.Vector3.Zero();
  28251. this._t1 = BABYLON.Vector3.Zero();
  28252. this._t2 = BABYLON.Vector3.Zero();
  28253. }
  28254. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  28255. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  28256. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  28257. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  28258. this._t1.subtractInPlace(this._t0);
  28259. this._t2.subtractInPlace(this._t0);
  28260. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28261. this._cachedTextureMatrix.m[0] = this._t1.x;
  28262. this._cachedTextureMatrix.m[1] = this._t1.y;
  28263. this._cachedTextureMatrix.m[2] = this._t1.z;
  28264. this._cachedTextureMatrix.m[4] = this._t2.x;
  28265. this._cachedTextureMatrix.m[5] = this._t2.y;
  28266. this._cachedTextureMatrix.m[6] = this._t2.z;
  28267. this._cachedTextureMatrix.m[8] = this._t0.x;
  28268. this._cachedTextureMatrix.m[9] = this._t0.y;
  28269. this._cachedTextureMatrix.m[10] = this._t0.z;
  28270. var scene = this.getScene();
  28271. if (!scene) {
  28272. return this._cachedTextureMatrix;
  28273. }
  28274. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  28275. return mat.hasTexture(_this);
  28276. });
  28277. return this._cachedTextureMatrix;
  28278. };
  28279. Texture.prototype.getReflectionTextureMatrix = function () {
  28280. var _this = this;
  28281. var scene = this.getScene();
  28282. if (!scene) {
  28283. return this._cachedTextureMatrix;
  28284. }
  28285. if (this.uOffset === this._cachedUOffset &&
  28286. this.vOffset === this._cachedVOffset &&
  28287. this.uScale === this._cachedUScale &&
  28288. this.vScale === this._cachedVScale &&
  28289. this.coordinatesMode === this._cachedCoordinatesMode) {
  28290. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  28291. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  28292. return this._cachedTextureMatrix;
  28293. }
  28294. }
  28295. else {
  28296. return this._cachedTextureMatrix;
  28297. }
  28298. }
  28299. if (!this._cachedTextureMatrix) {
  28300. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  28301. }
  28302. if (!this._projectionModeMatrix) {
  28303. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  28304. }
  28305. this._cachedUOffset = this.uOffset;
  28306. this._cachedVOffset = this.vOffset;
  28307. this._cachedUScale = this.uScale;
  28308. this._cachedVScale = this.vScale;
  28309. this._cachedCoordinatesMode = this.coordinatesMode;
  28310. switch (this.coordinatesMode) {
  28311. case Texture.PLANAR_MODE:
  28312. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28313. this._cachedTextureMatrix[0] = this.uScale;
  28314. this._cachedTextureMatrix[5] = this.vScale;
  28315. this._cachedTextureMatrix[12] = this.uOffset;
  28316. this._cachedTextureMatrix[13] = this.vOffset;
  28317. break;
  28318. case Texture.PROJECTION_MODE:
  28319. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  28320. this._projectionModeMatrix.m[0] = 0.5;
  28321. this._projectionModeMatrix.m[5] = -0.5;
  28322. this._projectionModeMatrix.m[10] = 0.0;
  28323. this._projectionModeMatrix.m[12] = 0.5;
  28324. this._projectionModeMatrix.m[13] = 0.5;
  28325. this._projectionModeMatrix.m[14] = 1.0;
  28326. this._projectionModeMatrix.m[15] = 1.0;
  28327. var projectionMatrix = scene.getProjectionMatrix();
  28328. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  28329. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  28330. break;
  28331. default:
  28332. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  28333. break;
  28334. }
  28335. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  28336. return (mat.getActiveTextures().indexOf(_this) !== -1);
  28337. });
  28338. return this._cachedTextureMatrix;
  28339. };
  28340. Texture.prototype.clone = function () {
  28341. var _this = this;
  28342. return BABYLON.SerializationHelper.Clone(function () {
  28343. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  28344. }, this);
  28345. };
  28346. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  28347. get: function () {
  28348. if (!this._onLoadObservable) {
  28349. this._onLoadObservable = new BABYLON.Observable();
  28350. }
  28351. return this._onLoadObservable;
  28352. },
  28353. enumerable: true,
  28354. configurable: true
  28355. });
  28356. Texture.prototype.serialize = function () {
  28357. var serializationObject = _super.prototype.serialize.call(this);
  28358. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  28359. serializationObject.base64String = this._buffer;
  28360. serializationObject.name = serializationObject.name.replace("data:", "");
  28361. }
  28362. return serializationObject;
  28363. };
  28364. Texture.prototype.getClassName = function () {
  28365. return "Texture";
  28366. };
  28367. Texture.prototype.dispose = function () {
  28368. _super.prototype.dispose.call(this);
  28369. if (this.onLoadObservable) {
  28370. this.onLoadObservable.clear();
  28371. this._onLoadObservable = null;
  28372. }
  28373. this._delayedOnLoad = null;
  28374. this._delayedOnError = null;
  28375. };
  28376. // Statics
  28377. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  28378. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28379. if (onLoad === void 0) { onLoad = null; }
  28380. if (onError === void 0) { onError = null; }
  28381. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28382. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  28383. };
  28384. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  28385. if (parsedTexture.customType) {
  28386. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  28387. // Update Sampling Mode
  28388. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  28389. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  28390. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  28391. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  28392. }
  28393. }
  28394. return parsedCustomTexture;
  28395. }
  28396. if (parsedTexture.isCube) {
  28397. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  28398. }
  28399. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  28400. return null;
  28401. }
  28402. var texture = BABYLON.SerializationHelper.Parse(function () {
  28403. var generateMipMaps = true;
  28404. if (parsedTexture.noMipmap) {
  28405. generateMipMaps = false;
  28406. }
  28407. if (parsedTexture.mirrorPlane) {
  28408. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  28409. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  28410. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  28411. return mirrorTexture;
  28412. }
  28413. else if (parsedTexture.isRenderTarget) {
  28414. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  28415. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  28416. return renderTargetTexture;
  28417. }
  28418. else {
  28419. var texture;
  28420. if (parsedTexture.base64String) {
  28421. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  28422. }
  28423. else {
  28424. var url = rootUrl + parsedTexture.name;
  28425. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  28426. url = parsedTexture.url;
  28427. }
  28428. texture = new Texture(url, scene, !generateMipMaps);
  28429. }
  28430. return texture;
  28431. }
  28432. }, parsedTexture, scene);
  28433. // Update Sampling Mode
  28434. if (parsedTexture.samplingMode) {
  28435. var sampling = parsedTexture.samplingMode;
  28436. if (texture._samplingMode !== sampling) {
  28437. texture.updateSamplingMode(sampling);
  28438. }
  28439. }
  28440. // Animations
  28441. if (parsedTexture.animations) {
  28442. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  28443. var parsedAnimation = parsedTexture.animations[animationIndex];
  28444. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28445. }
  28446. }
  28447. return texture;
  28448. };
  28449. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  28450. if (deleteBuffer === void 0) { deleteBuffer = false; }
  28451. if (noMipmap === void 0) { noMipmap = false; }
  28452. if (invertY === void 0) { invertY = true; }
  28453. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  28454. if (onLoad === void 0) { onLoad = null; }
  28455. if (onError === void 0) { onError = null; }
  28456. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  28457. if (name.substr(0, 5) !== "data:") {
  28458. name = "data:" + name;
  28459. }
  28460. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  28461. };
  28462. // Constants
  28463. Texture.NEAREST_SAMPLINGMODE = 1;
  28464. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  28465. Texture.BILINEAR_SAMPLINGMODE = 2;
  28466. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  28467. Texture.TRILINEAR_SAMPLINGMODE = 3;
  28468. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  28469. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  28470. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  28471. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  28472. Texture.NEAREST_LINEAR = 7;
  28473. Texture.NEAREST_NEAREST = 8;
  28474. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  28475. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  28476. Texture.LINEAR_LINEAR = 11;
  28477. Texture.LINEAR_NEAREST = 12;
  28478. Texture.EXPLICIT_MODE = 0;
  28479. Texture.SPHERICAL_MODE = 1;
  28480. Texture.PLANAR_MODE = 2;
  28481. Texture.CUBIC_MODE = 3;
  28482. Texture.PROJECTION_MODE = 4;
  28483. Texture.SKYBOX_MODE = 5;
  28484. Texture.INVCUBIC_MODE = 6;
  28485. Texture.EQUIRECTANGULAR_MODE = 7;
  28486. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  28487. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  28488. Texture.CLAMP_ADDRESSMODE = 0;
  28489. Texture.WRAP_ADDRESSMODE = 1;
  28490. Texture.MIRROR_ADDRESSMODE = 2;
  28491. /**
  28492. * 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
  28493. */
  28494. Texture.UseSerializedUrlIfAny = false;
  28495. __decorate([
  28496. BABYLON.serialize()
  28497. ], Texture.prototype, "url", void 0);
  28498. __decorate([
  28499. BABYLON.serialize()
  28500. ], Texture.prototype, "uOffset", void 0);
  28501. __decorate([
  28502. BABYLON.serialize()
  28503. ], Texture.prototype, "vOffset", void 0);
  28504. __decorate([
  28505. BABYLON.serialize()
  28506. ], Texture.prototype, "uScale", void 0);
  28507. __decorate([
  28508. BABYLON.serialize()
  28509. ], Texture.prototype, "vScale", void 0);
  28510. __decorate([
  28511. BABYLON.serialize()
  28512. ], Texture.prototype, "uAng", void 0);
  28513. __decorate([
  28514. BABYLON.serialize()
  28515. ], Texture.prototype, "vAng", void 0);
  28516. __decorate([
  28517. BABYLON.serialize()
  28518. ], Texture.prototype, "wAng", void 0);
  28519. __decorate([
  28520. BABYLON.serialize()
  28521. ], Texture.prototype, "isBlocking", null);
  28522. return Texture;
  28523. }(BABYLON.BaseTexture));
  28524. BABYLON.Texture = Texture;
  28525. })(BABYLON || (BABYLON = {}));
  28526. //# sourceMappingURL=babylon.texture.js.map
  28527. "use strict";
  28528. var BABYLON;
  28529. (function (BABYLON) {
  28530. var _InstancesBatch = /** @class */ (function () {
  28531. function _InstancesBatch() {
  28532. this.mustReturn = false;
  28533. this.visibleInstances = new Array();
  28534. this.renderSelf = new Array();
  28535. }
  28536. return _InstancesBatch;
  28537. }());
  28538. BABYLON._InstancesBatch = _InstancesBatch;
  28539. var Mesh = /** @class */ (function (_super) {
  28540. __extends(Mesh, _super);
  28541. /**
  28542. * @constructor
  28543. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  28544. * @param {Scene} scene The scene to add this mesh to.
  28545. * @param {Node} parent The parent of this mesh, if it has one
  28546. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  28547. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  28548. * When false, achieved by calling a clone(), also passing False.
  28549. * This will make creation of children, recursive.
  28550. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  28551. */
  28552. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  28553. if (scene === void 0) { scene = null; }
  28554. if (parent === void 0) { parent = null; }
  28555. if (source === void 0) { source = null; }
  28556. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28557. var _this = _super.call(this, name, scene) || this;
  28558. // Events
  28559. /**
  28560. * An event triggered before rendering the mesh
  28561. */
  28562. _this.onBeforeRenderObservable = new BABYLON.Observable();
  28563. /**
  28564. * An event triggered after rendering the mesh
  28565. */
  28566. _this.onAfterRenderObservable = new BABYLON.Observable();
  28567. /**
  28568. * An event triggered before drawing the mesh
  28569. */
  28570. _this.onBeforeDrawObservable = new BABYLON.Observable();
  28571. // Members
  28572. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28573. _this.instances = new Array();
  28574. _this._LODLevels = new Array();
  28575. _this._visibleInstances = {};
  28576. _this._renderIdForInstances = new Array();
  28577. _this._batchCache = new _InstancesBatch();
  28578. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  28579. // Use by builder only to know what orientation were the mesh build in.
  28580. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  28581. _this.overrideMaterialSideOrientation = null;
  28582. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  28583. // Will be used to save a source mesh reference, If any
  28584. _this._source = null;
  28585. scene = _this.getScene();
  28586. if (source) {
  28587. // Source mesh
  28588. _this._source = source;
  28589. // Geometry
  28590. if (source._geometry) {
  28591. source._geometry.applyToMesh(_this);
  28592. }
  28593. // Deep copy
  28594. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  28595. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  28596. // Metadata
  28597. if (source.metadata && source.metadata.clone) {
  28598. _this.metadata = source.metadata.clone();
  28599. }
  28600. else {
  28601. _this.metadata = source.metadata;
  28602. }
  28603. // Tags
  28604. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  28605. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  28606. }
  28607. // Parent
  28608. _this.parent = source.parent;
  28609. // Pivot
  28610. _this.setPivotMatrix(source.getPivotMatrix());
  28611. _this.id = name + "." + source.id;
  28612. // Material
  28613. _this.material = source.material;
  28614. var index;
  28615. if (!doNotCloneChildren) {
  28616. // Children
  28617. var directDescendants = source.getDescendants(true);
  28618. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  28619. var child = directDescendants[index_1];
  28620. if (child.clone) {
  28621. child.clone(name + "." + child.name, _this);
  28622. }
  28623. }
  28624. }
  28625. // Physics clone
  28626. var physicsEngine = _this.getScene().getPhysicsEngine();
  28627. if (clonePhysicsImpostor && physicsEngine) {
  28628. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  28629. if (impostor) {
  28630. _this.physicsImpostor = impostor.clone(_this);
  28631. }
  28632. }
  28633. // Particles
  28634. for (index = 0; index < scene.particleSystems.length; index++) {
  28635. var system = scene.particleSystems[index];
  28636. if (system.emitter === source) {
  28637. system.clone(system.name, _this);
  28638. }
  28639. }
  28640. _this.computeWorldMatrix(true);
  28641. }
  28642. // Parent
  28643. if (parent !== null) {
  28644. _this.parent = parent;
  28645. }
  28646. return _this;
  28647. }
  28648. Object.defineProperty(Mesh, "FRONTSIDE", {
  28649. /**
  28650. * Mesh side orientation : usually the external or front surface
  28651. */
  28652. get: function () {
  28653. return Mesh._FRONTSIDE;
  28654. },
  28655. enumerable: true,
  28656. configurable: true
  28657. });
  28658. Object.defineProperty(Mesh, "BACKSIDE", {
  28659. /**
  28660. * Mesh side orientation : usually the internal or back surface
  28661. */
  28662. get: function () {
  28663. return Mesh._BACKSIDE;
  28664. },
  28665. enumerable: true,
  28666. configurable: true
  28667. });
  28668. Object.defineProperty(Mesh, "DOUBLESIDE", {
  28669. /**
  28670. * Mesh side orientation : both internal and external or front and back surfaces
  28671. */
  28672. get: function () {
  28673. return Mesh._DOUBLESIDE;
  28674. },
  28675. enumerable: true,
  28676. configurable: true
  28677. });
  28678. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  28679. /**
  28680. * Mesh side orientation : by default, `FRONTSIDE`
  28681. */
  28682. get: function () {
  28683. return Mesh._DEFAULTSIDE;
  28684. },
  28685. enumerable: true,
  28686. configurable: true
  28687. });
  28688. Object.defineProperty(Mesh, "NO_CAP", {
  28689. /**
  28690. * Mesh cap setting : no cap
  28691. */
  28692. get: function () {
  28693. return Mesh._NO_CAP;
  28694. },
  28695. enumerable: true,
  28696. configurable: true
  28697. });
  28698. Object.defineProperty(Mesh, "CAP_START", {
  28699. /**
  28700. * Mesh cap setting : one cap at the beginning of the mesh
  28701. */
  28702. get: function () {
  28703. return Mesh._CAP_START;
  28704. },
  28705. enumerable: true,
  28706. configurable: true
  28707. });
  28708. Object.defineProperty(Mesh, "CAP_END", {
  28709. /**
  28710. * Mesh cap setting : one cap at the end of the mesh
  28711. */
  28712. get: function () {
  28713. return Mesh._CAP_END;
  28714. },
  28715. enumerable: true,
  28716. configurable: true
  28717. });
  28718. Object.defineProperty(Mesh, "CAP_ALL", {
  28719. /**
  28720. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  28721. */
  28722. get: function () {
  28723. return Mesh._CAP_ALL;
  28724. },
  28725. enumerable: true,
  28726. configurable: true
  28727. });
  28728. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  28729. set: function (callback) {
  28730. if (this._onBeforeDrawObserver) {
  28731. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  28732. }
  28733. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  28734. },
  28735. enumerable: true,
  28736. configurable: true
  28737. });
  28738. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  28739. get: function () {
  28740. return this._morphTargetManager;
  28741. },
  28742. set: function (value) {
  28743. if (this._morphTargetManager === value) {
  28744. return;
  28745. }
  28746. this._morphTargetManager = value;
  28747. this._syncGeometryWithMorphTargetManager();
  28748. },
  28749. enumerable: true,
  28750. configurable: true
  28751. });
  28752. Object.defineProperty(Mesh.prototype, "source", {
  28753. get: function () {
  28754. return this._source;
  28755. },
  28756. enumerable: true,
  28757. configurable: true
  28758. });
  28759. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  28760. get: function () {
  28761. return this._unIndexed;
  28762. },
  28763. set: function (value) {
  28764. if (this._unIndexed !== value) {
  28765. this._unIndexed = value;
  28766. this._markSubMeshesAsAttributesDirty();
  28767. }
  28768. },
  28769. enumerable: true,
  28770. configurable: true
  28771. });
  28772. // Methods
  28773. /**
  28774. * Returns the string "Mesh".
  28775. */
  28776. Mesh.prototype.getClassName = function () {
  28777. return "Mesh";
  28778. };
  28779. /**
  28780. * Returns a string.
  28781. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28782. */
  28783. Mesh.prototype.toString = function (fullDetails) {
  28784. var ret = _super.prototype.toString.call(this, fullDetails);
  28785. ret += ", n vertices: " + this.getTotalVertices();
  28786. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  28787. if (this.animations) {
  28788. for (var i = 0; i < this.animations.length; i++) {
  28789. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28790. }
  28791. }
  28792. if (fullDetails) {
  28793. if (this._geometry) {
  28794. var ib = this.getIndices();
  28795. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28796. if (vb && ib) {
  28797. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28798. }
  28799. }
  28800. else {
  28801. ret += ", flat shading: UNKNOWN";
  28802. }
  28803. }
  28804. return ret;
  28805. };
  28806. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28807. /**
  28808. * True if the mesh has some Levels Of Details (LOD).
  28809. * Returns a boolean.
  28810. */
  28811. get: function () {
  28812. return this._LODLevels.length > 0;
  28813. },
  28814. enumerable: true,
  28815. configurable: true
  28816. });
  28817. /**
  28818. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28819. * @returns an array of {BABYLON.MeshLODLevel}
  28820. */
  28821. Mesh.prototype.getLODLevels = function () {
  28822. return this._LODLevels;
  28823. };
  28824. Mesh.prototype._sortLODLevels = function () {
  28825. this._LODLevels.sort(function (a, b) {
  28826. if (a.distance < b.distance) {
  28827. return 1;
  28828. }
  28829. if (a.distance > b.distance) {
  28830. return -1;
  28831. }
  28832. return 0;
  28833. });
  28834. };
  28835. /**
  28836. * Add a mesh as LOD level triggered at the given distance.
  28837. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28838. * @param {number} distance The distance from the center of the object to show this level
  28839. * @param {Mesh} mesh The mesh to be added as LOD level
  28840. * @return {Mesh} This mesh (for chaining)
  28841. */
  28842. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28843. if (mesh && mesh._masterMesh) {
  28844. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28845. return this;
  28846. }
  28847. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28848. this._LODLevels.push(level);
  28849. if (mesh) {
  28850. mesh._masterMesh = this;
  28851. }
  28852. this._sortLODLevels();
  28853. return this;
  28854. };
  28855. /**
  28856. * Returns the LOD level mesh at the passed distance or null if not found.
  28857. * It is related to the method `addLODLevel(distance, mesh)`.
  28858. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28859. * Returns an object Mesh or `null`.
  28860. */
  28861. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28862. for (var index = 0; index < this._LODLevels.length; index++) {
  28863. var level = this._LODLevels[index];
  28864. if (level.distance === distance) {
  28865. return level.mesh;
  28866. }
  28867. }
  28868. return null;
  28869. };
  28870. /**
  28871. * Remove a mesh from the LOD array
  28872. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28873. * @param {Mesh} mesh The mesh to be removed.
  28874. * @return {Mesh} This mesh (for chaining)
  28875. */
  28876. Mesh.prototype.removeLODLevel = function (mesh) {
  28877. for (var index = 0; index < this._LODLevels.length; index++) {
  28878. if (this._LODLevels[index].mesh === mesh) {
  28879. this._LODLevels.splice(index, 1);
  28880. if (mesh) {
  28881. mesh._masterMesh = null;
  28882. }
  28883. }
  28884. }
  28885. this._sortLODLevels();
  28886. return this;
  28887. };
  28888. /**
  28889. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28890. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28891. */
  28892. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28893. if (!this._LODLevels || this._LODLevels.length === 0) {
  28894. return this;
  28895. }
  28896. var bSphere;
  28897. if (boundingSphere) {
  28898. bSphere = boundingSphere;
  28899. }
  28900. else {
  28901. var boundingInfo = this.getBoundingInfo();
  28902. bSphere = boundingInfo.boundingSphere;
  28903. }
  28904. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28905. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28906. if (this.onLODLevelSelection) {
  28907. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28908. }
  28909. return this;
  28910. }
  28911. for (var index = 0; index < this._LODLevels.length; index++) {
  28912. var level = this._LODLevels[index];
  28913. if (level.distance < distanceToCamera) {
  28914. if (level.mesh) {
  28915. level.mesh._preActivate();
  28916. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28917. }
  28918. if (this.onLODLevelSelection) {
  28919. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28920. }
  28921. return level.mesh;
  28922. }
  28923. }
  28924. if (this.onLODLevelSelection) {
  28925. this.onLODLevelSelection(distanceToCamera, this, this);
  28926. }
  28927. return this;
  28928. };
  28929. Object.defineProperty(Mesh.prototype, "geometry", {
  28930. /**
  28931. * Returns the mesh internal Geometry object.
  28932. */
  28933. get: function () {
  28934. return this._geometry;
  28935. },
  28936. enumerable: true,
  28937. configurable: true
  28938. });
  28939. /**
  28940. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28941. */
  28942. Mesh.prototype.getTotalVertices = function () {
  28943. if (this._geometry === null || this._geometry === undefined) {
  28944. return 0;
  28945. }
  28946. return this._geometry.getTotalVertices();
  28947. };
  28948. /**
  28949. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28950. * 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.
  28951. * You can force the copy with forceCopy === true
  28952. * Returns null if the mesh has no geometry or no vertex buffer.
  28953. * Possible `kind` values :
  28954. * - BABYLON.VertexBuffer.PositionKind
  28955. * - BABYLON.VertexBuffer.UVKind
  28956. * - BABYLON.VertexBuffer.UV2Kind
  28957. * - BABYLON.VertexBuffer.UV3Kind
  28958. * - BABYLON.VertexBuffer.UV4Kind
  28959. * - BABYLON.VertexBuffer.UV5Kind
  28960. * - BABYLON.VertexBuffer.UV6Kind
  28961. * - BABYLON.VertexBuffer.ColorKind
  28962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28966. */
  28967. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28968. if (!this._geometry) {
  28969. return null;
  28970. }
  28971. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28972. };
  28973. /**
  28974. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28975. * Returns `null` if the mesh has no geometry.
  28976. * Possible `kind` values :
  28977. * - BABYLON.VertexBuffer.PositionKind
  28978. * - BABYLON.VertexBuffer.UVKind
  28979. * - BABYLON.VertexBuffer.UV2Kind
  28980. * - BABYLON.VertexBuffer.UV3Kind
  28981. * - BABYLON.VertexBuffer.UV4Kind
  28982. * - BABYLON.VertexBuffer.UV5Kind
  28983. * - BABYLON.VertexBuffer.UV6Kind
  28984. * - BABYLON.VertexBuffer.ColorKind
  28985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28989. */
  28990. Mesh.prototype.getVertexBuffer = function (kind) {
  28991. if (!this._geometry) {
  28992. return null;
  28993. }
  28994. return this._geometry.getVertexBuffer(kind);
  28995. };
  28996. /**
  28997. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28998. * Possible `kind` values :
  28999. * - BABYLON.VertexBuffer.PositionKind
  29000. * - BABYLON.VertexBuffer.UVKind
  29001. * - BABYLON.VertexBuffer.UV2Kind
  29002. * - BABYLON.VertexBuffer.UV3Kind
  29003. * - BABYLON.VertexBuffer.UV4Kind
  29004. * - BABYLON.VertexBuffer.UV5Kind
  29005. * - BABYLON.VertexBuffer.UV6Kind
  29006. * - BABYLON.VertexBuffer.ColorKind
  29007. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29008. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29009. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29010. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29011. */
  29012. Mesh.prototype.isVerticesDataPresent = function (kind) {
  29013. if (!this._geometry) {
  29014. if (this._delayInfo) {
  29015. return this._delayInfo.indexOf(kind) !== -1;
  29016. }
  29017. return false;
  29018. }
  29019. return this._geometry.isVerticesDataPresent(kind);
  29020. };
  29021. /**
  29022. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  29023. * Possible `kind` values :
  29024. * - BABYLON.VertexBuffer.PositionKind
  29025. * - BABYLON.VertexBuffer.UVKind
  29026. * - BABYLON.VertexBuffer.UV2Kind
  29027. * - BABYLON.VertexBuffer.UV3Kind
  29028. * - BABYLON.VertexBuffer.UV4Kind
  29029. * - BABYLON.VertexBuffer.UV5Kind
  29030. * - BABYLON.VertexBuffer.UV6Kind
  29031. * - BABYLON.VertexBuffer.ColorKind
  29032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29036. */
  29037. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  29038. if (!this._geometry) {
  29039. if (this._delayInfo) {
  29040. return this._delayInfo.indexOf(kind) !== -1;
  29041. }
  29042. return false;
  29043. }
  29044. return this._geometry.isVertexBufferUpdatable(kind);
  29045. };
  29046. /**
  29047. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  29048. * Possible `kind` values :
  29049. * - BABYLON.VertexBuffer.PositionKind
  29050. * - BABYLON.VertexBuffer.UVKind
  29051. * - BABYLON.VertexBuffer.UV2Kind
  29052. * - BABYLON.VertexBuffer.UV3Kind
  29053. * - BABYLON.VertexBuffer.UV4Kind
  29054. * - BABYLON.VertexBuffer.UV5Kind
  29055. * - BABYLON.VertexBuffer.UV6Kind
  29056. * - BABYLON.VertexBuffer.ColorKind
  29057. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29058. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29059. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29060. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29061. */
  29062. Mesh.prototype.getVerticesDataKinds = function () {
  29063. if (!this._geometry) {
  29064. var result = new Array();
  29065. if (this._delayInfo) {
  29066. this._delayInfo.forEach(function (kind, index, array) {
  29067. result.push(kind);
  29068. });
  29069. }
  29070. return result;
  29071. }
  29072. return this._geometry.getVerticesDataKinds();
  29073. };
  29074. /**
  29075. * Returns a positive integer : the total number of indices in this mesh geometry.
  29076. * Returns zero if the mesh has no geometry.
  29077. */
  29078. Mesh.prototype.getTotalIndices = function () {
  29079. if (!this._geometry) {
  29080. return 0;
  29081. }
  29082. return this._geometry.getTotalIndices();
  29083. };
  29084. /**
  29085. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  29086. * 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.
  29087. * Returns an empty array if the mesh has no geometry.
  29088. */
  29089. Mesh.prototype.getIndices = function (copyWhenShared) {
  29090. if (!this._geometry) {
  29091. return [];
  29092. }
  29093. return this._geometry.getIndices(copyWhenShared);
  29094. };
  29095. Object.defineProperty(Mesh.prototype, "isBlocked", {
  29096. get: function () {
  29097. return this._masterMesh !== null && this._masterMesh !== undefined;
  29098. },
  29099. enumerable: true,
  29100. configurable: true
  29101. });
  29102. /**
  29103. * Determine if the current mesh is ready to be rendered
  29104. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  29105. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  29106. * @returns true if all associated assets are ready (material, textures, shaders)
  29107. */
  29108. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  29109. if (completeCheck === void 0) { completeCheck = false; }
  29110. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  29111. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29112. return false;
  29113. }
  29114. if (!_super.prototype.isReady.call(this, completeCheck)) {
  29115. return false;
  29116. }
  29117. if (!this.subMeshes || this.subMeshes.length === 0) {
  29118. return true;
  29119. }
  29120. if (!completeCheck) {
  29121. return true;
  29122. }
  29123. var engine = this.getEngine();
  29124. var scene = this.getScene();
  29125. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  29126. this.computeWorldMatrix();
  29127. var mat = this.material || scene.defaultMaterial;
  29128. if (mat) {
  29129. if (mat.storeEffectOnSubMeshes) {
  29130. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  29131. var subMesh = _a[_i];
  29132. var effectiveMaterial = subMesh.getMaterial();
  29133. if (effectiveMaterial) {
  29134. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29135. return false;
  29136. }
  29137. }
  29138. }
  29139. }
  29140. else {
  29141. if (!mat.isReady(this, hardwareInstancedRendering)) {
  29142. return false;
  29143. }
  29144. }
  29145. }
  29146. // Shadows
  29147. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  29148. var light = _c[_b];
  29149. var generator = light.getShadowGenerator();
  29150. if (generator) {
  29151. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  29152. var subMesh = _e[_d];
  29153. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  29154. return false;
  29155. }
  29156. }
  29157. }
  29158. }
  29159. // LOD
  29160. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  29161. var lod = _g[_f];
  29162. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  29163. return false;
  29164. }
  29165. }
  29166. return true;
  29167. };
  29168. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  29169. /**
  29170. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  29171. * This property is pertinent only for updatable parametric shapes.
  29172. */
  29173. get: function () {
  29174. return this._areNormalsFrozen;
  29175. },
  29176. enumerable: true,
  29177. configurable: true
  29178. });
  29179. /**
  29180. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  29181. * It has no effect at all on other shapes.
  29182. * It prevents the mesh normals from being recomputed on next `positions` array update.
  29183. * Returns the Mesh.
  29184. */
  29185. Mesh.prototype.freezeNormals = function () {
  29186. this._areNormalsFrozen = true;
  29187. return this;
  29188. };
  29189. /**
  29190. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  29191. * It has no effect at all on other shapes.
  29192. * It reactivates the mesh normals computation if it was previously frozen.
  29193. * Returns the Mesh.
  29194. */
  29195. Mesh.prototype.unfreezeNormals = function () {
  29196. this._areNormalsFrozen = false;
  29197. return this;
  29198. };
  29199. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  29200. /**
  29201. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  29202. */
  29203. set: function (count) {
  29204. this._overridenInstanceCount = count;
  29205. },
  29206. enumerable: true,
  29207. configurable: true
  29208. });
  29209. // Methods
  29210. Mesh.prototype._preActivate = function () {
  29211. var sceneRenderId = this.getScene().getRenderId();
  29212. if (this._preActivateId === sceneRenderId) {
  29213. return this;
  29214. }
  29215. this._preActivateId = sceneRenderId;
  29216. this._visibleInstances = null;
  29217. return this;
  29218. };
  29219. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  29220. if (this._visibleInstances) {
  29221. this._visibleInstances.intermediateDefaultRenderId = renderId;
  29222. }
  29223. return this;
  29224. };
  29225. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  29226. if (!this._visibleInstances) {
  29227. this._visibleInstances = {};
  29228. this._visibleInstances.defaultRenderId = renderId;
  29229. this._visibleInstances.selfDefaultRenderId = this._renderId;
  29230. }
  29231. if (!this._visibleInstances[renderId]) {
  29232. this._visibleInstances[renderId] = new Array();
  29233. }
  29234. this._visibleInstances[renderId].push(instance);
  29235. return this;
  29236. };
  29237. /**
  29238. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  29239. * This means the mesh underlying bounding box and sphere are recomputed.
  29240. * Returns the Mesh.
  29241. */
  29242. Mesh.prototype.refreshBoundingInfo = function () {
  29243. return this._refreshBoundingInfo(false);
  29244. };
  29245. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  29246. if (this._boundingInfo && this._boundingInfo.isLocked) {
  29247. return this;
  29248. }
  29249. var data = this._getPositionData(applySkeleton);
  29250. if (data) {
  29251. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  29252. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29253. }
  29254. if (this.subMeshes) {
  29255. for (var index = 0; index < this.subMeshes.length; index++) {
  29256. this.subMeshes[index].refreshBoundingInfo();
  29257. }
  29258. }
  29259. this._updateBoundingInfo();
  29260. return this;
  29261. };
  29262. Mesh.prototype._getPositionData = function (applySkeleton) {
  29263. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29264. if (data && applySkeleton && this.skeleton) {
  29265. data = BABYLON.Tools.Slice(data);
  29266. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29267. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29268. if (matricesWeightsData && matricesIndicesData) {
  29269. var needExtras = this.numBoneInfluencers > 4;
  29270. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29271. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29272. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  29273. var tempVector = BABYLON.Tmp.Vector3[0];
  29274. var finalMatrix = BABYLON.Tmp.Matrix[0];
  29275. var tempMatrix = BABYLON.Tmp.Matrix[1];
  29276. var matWeightIdx = 0;
  29277. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  29278. finalMatrix.reset();
  29279. var inf;
  29280. var weight;
  29281. for (inf = 0; inf < 4; inf++) {
  29282. weight = matricesWeightsData[matWeightIdx + inf];
  29283. if (weight <= 0)
  29284. break;
  29285. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29286. finalMatrix.addToSelf(tempMatrix);
  29287. }
  29288. if (needExtras) {
  29289. for (inf = 0; inf < 4; inf++) {
  29290. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29291. if (weight <= 0)
  29292. break;
  29293. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29294. finalMatrix.addToSelf(tempMatrix);
  29295. }
  29296. }
  29297. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  29298. tempVector.toArray(data, index);
  29299. }
  29300. }
  29301. }
  29302. return data;
  29303. };
  29304. Mesh.prototype._createGlobalSubMesh = function (force) {
  29305. var totalVertices = this.getTotalVertices();
  29306. if (!totalVertices || !this.getIndices()) {
  29307. return null;
  29308. }
  29309. // Check if we need to recreate the submeshes
  29310. if (this.subMeshes && this.subMeshes.length > 0) {
  29311. var ib = this.getIndices();
  29312. if (!ib) {
  29313. return null;
  29314. }
  29315. var totalIndices = ib.length;
  29316. var needToRecreate = false;
  29317. if (force) {
  29318. needToRecreate = true;
  29319. }
  29320. else {
  29321. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  29322. var submesh = _a[_i];
  29323. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  29324. needToRecreate = true;
  29325. break;
  29326. }
  29327. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  29328. needToRecreate = true;
  29329. break;
  29330. }
  29331. }
  29332. }
  29333. if (!needToRecreate) {
  29334. return this.subMeshes[0];
  29335. }
  29336. }
  29337. this.releaseSubMeshes();
  29338. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  29339. };
  29340. Mesh.prototype.subdivide = function (count) {
  29341. if (count < 1) {
  29342. return;
  29343. }
  29344. var totalIndices = this.getTotalIndices();
  29345. var subdivisionSize = (totalIndices / count) | 0;
  29346. var offset = 0;
  29347. // Ensure that subdivisionSize is a multiple of 3
  29348. while (subdivisionSize % 3 !== 0) {
  29349. subdivisionSize++;
  29350. }
  29351. this.releaseSubMeshes();
  29352. for (var index = 0; index < count; index++) {
  29353. if (offset >= totalIndices) {
  29354. break;
  29355. }
  29356. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  29357. offset += subdivisionSize;
  29358. }
  29359. this.synchronizeInstances();
  29360. };
  29361. /**
  29362. * Sets the vertex data of the mesh geometry for the requested `kind`.
  29363. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  29364. * The `data` are either a numeric array either a Float32Array.
  29365. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  29366. * 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).
  29367. * Note that a new underlying VertexBuffer object is created each call.
  29368. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  29369. *
  29370. * Possible `kind` values :
  29371. * - BABYLON.VertexBuffer.PositionKind
  29372. * - BABYLON.VertexBuffer.UVKind
  29373. * - BABYLON.VertexBuffer.UV2Kind
  29374. * - BABYLON.VertexBuffer.UV3Kind
  29375. * - BABYLON.VertexBuffer.UV4Kind
  29376. * - BABYLON.VertexBuffer.UV5Kind
  29377. * - BABYLON.VertexBuffer.UV6Kind
  29378. * - BABYLON.VertexBuffer.ColorKind
  29379. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29380. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29381. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29382. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29383. *
  29384. * Returns the Mesh.
  29385. */
  29386. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  29387. if (updatable === void 0) { updatable = false; }
  29388. if (!this._geometry) {
  29389. var vertexData = new BABYLON.VertexData();
  29390. vertexData.set(data, kind);
  29391. var scene = this.getScene();
  29392. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  29393. }
  29394. else {
  29395. this._geometry.setVerticesData(kind, data, updatable, stride);
  29396. }
  29397. return this;
  29398. };
  29399. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  29400. if (updatable === void 0) { updatable = true; }
  29401. var vb = this.getVertexBuffer(kind);
  29402. if (!vb || vb.isUpdatable() === updatable) {
  29403. return;
  29404. }
  29405. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  29406. };
  29407. /**
  29408. * Sets the mesh VertexBuffer.
  29409. * Returns the Mesh.
  29410. */
  29411. Mesh.prototype.setVerticesBuffer = function (buffer) {
  29412. if (!this._geometry) {
  29413. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  29414. }
  29415. this._geometry.setVerticesBuffer(buffer);
  29416. return this;
  29417. };
  29418. /**
  29419. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  29420. * If the mesh has no geometry, it is simply returned as it is.
  29421. * The `data` are either a numeric array either a Float32Array.
  29422. * No new underlying VertexBuffer object is created.
  29423. * 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.
  29424. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  29425. *
  29426. * Possible `kind` values :
  29427. * - BABYLON.VertexBuffer.PositionKind
  29428. * - BABYLON.VertexBuffer.UVKind
  29429. * - BABYLON.VertexBuffer.UV2Kind
  29430. * - BABYLON.VertexBuffer.UV3Kind
  29431. * - BABYLON.VertexBuffer.UV4Kind
  29432. * - BABYLON.VertexBuffer.UV5Kind
  29433. * - BABYLON.VertexBuffer.UV6Kind
  29434. * - BABYLON.VertexBuffer.ColorKind
  29435. * - BABYLON.VertexBuffer.MatricesIndicesKind
  29436. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  29437. * - BABYLON.VertexBuffer.MatricesWeightsKind
  29438. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  29439. *
  29440. * Returns the Mesh.
  29441. */
  29442. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  29443. if (!this._geometry) {
  29444. return this;
  29445. }
  29446. if (!makeItUnique) {
  29447. this._geometry.updateVerticesData(kind, data, updateExtends);
  29448. }
  29449. else {
  29450. this.makeGeometryUnique();
  29451. this.updateVerticesData(kind, data, updateExtends, false);
  29452. }
  29453. return this;
  29454. };
  29455. /**
  29456. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  29457. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  29458. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  29459. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  29460. * Returns the Mesh.
  29461. */
  29462. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  29463. if (computeNormals === void 0) { computeNormals = true; }
  29464. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29465. if (!positions) {
  29466. return this;
  29467. }
  29468. positionFunction(positions);
  29469. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  29470. if (computeNormals) {
  29471. var indices = this.getIndices();
  29472. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29473. if (!normals) {
  29474. return this;
  29475. }
  29476. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  29477. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  29478. }
  29479. return this;
  29480. };
  29481. /**
  29482. * Creates a un-shared specific occurence of the geometry for the mesh.
  29483. * Returns the Mesh.
  29484. */
  29485. Mesh.prototype.makeGeometryUnique = function () {
  29486. if (!this._geometry) {
  29487. return this;
  29488. }
  29489. var oldGeometry = this._geometry;
  29490. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  29491. oldGeometry.releaseForMesh(this, true);
  29492. geometry.applyToMesh(this);
  29493. return this;
  29494. };
  29495. /**
  29496. * Sets the mesh indices.
  29497. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  29498. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  29499. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  29500. * This method creates a new index buffer each call.
  29501. * Returns the Mesh.
  29502. */
  29503. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  29504. if (totalVertices === void 0) { totalVertices = null; }
  29505. if (updatable === void 0) { updatable = false; }
  29506. if (!this._geometry) {
  29507. var vertexData = new BABYLON.VertexData();
  29508. vertexData.indices = indices;
  29509. var scene = this.getScene();
  29510. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  29511. }
  29512. else {
  29513. this._geometry.setIndices(indices, totalVertices, updatable);
  29514. }
  29515. return this;
  29516. };
  29517. /**
  29518. * Update the current index buffer
  29519. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  29520. * Returns the Mesh.
  29521. */
  29522. Mesh.prototype.updateIndices = function (indices, offset) {
  29523. if (!this._geometry) {
  29524. return this;
  29525. }
  29526. this._geometry.updateIndices(indices, offset);
  29527. return this;
  29528. };
  29529. /**
  29530. * Invert the geometry to move from a right handed system to a left handed one.
  29531. * Returns the Mesh.
  29532. */
  29533. Mesh.prototype.toLeftHanded = function () {
  29534. if (!this._geometry) {
  29535. return this;
  29536. }
  29537. this._geometry.toLeftHanded();
  29538. return this;
  29539. };
  29540. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  29541. if (!this._geometry) {
  29542. return this;
  29543. }
  29544. var engine = this.getScene().getEngine();
  29545. // Wireframe
  29546. var indexToBind;
  29547. if (this._unIndexed) {
  29548. indexToBind = null;
  29549. }
  29550. else {
  29551. switch (fillMode) {
  29552. case BABYLON.Material.PointFillMode:
  29553. indexToBind = null;
  29554. break;
  29555. case BABYLON.Material.WireFrameFillMode:
  29556. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  29557. break;
  29558. default:
  29559. case BABYLON.Material.TriangleFillMode:
  29560. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  29561. break;
  29562. }
  29563. }
  29564. // VBOs
  29565. this._geometry._bind(effect, indexToBind);
  29566. return this;
  29567. };
  29568. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  29569. if (alternate === void 0) { alternate = false; }
  29570. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29571. return this;
  29572. }
  29573. this.onBeforeDrawObservable.notifyObservers(this);
  29574. var scene = this.getScene();
  29575. var engine = scene.getEngine();
  29576. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  29577. // or triangles as points
  29578. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  29579. }
  29580. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  29581. // Triangles as wireframe
  29582. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  29583. }
  29584. else {
  29585. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  29586. }
  29587. if (scene._isAlternateRenderingEnabled && !alternate) {
  29588. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  29589. if (!effect || !scene.activeCamera) {
  29590. return this;
  29591. }
  29592. scene._switchToAlternateCameraConfiguration(true);
  29593. this._effectiveMaterial.bindView(effect);
  29594. this._effectiveMaterial.bindViewProjection(effect);
  29595. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  29596. this._draw(subMesh, fillMode, instancesCount, true);
  29597. engine.setViewport(scene.activeCamera.viewport);
  29598. scene._switchToAlternateCameraConfiguration(false);
  29599. this._effectiveMaterial.bindView(effect);
  29600. this._effectiveMaterial.bindViewProjection(effect);
  29601. }
  29602. return this;
  29603. };
  29604. /**
  29605. * Registers for this mesh a javascript function called just before the rendering process.
  29606. * This function is passed the current mesh.
  29607. * Return the Mesh.
  29608. */
  29609. Mesh.prototype.registerBeforeRender = function (func) {
  29610. this.onBeforeRenderObservable.add(func);
  29611. return this;
  29612. };
  29613. /**
  29614. * Disposes a previously registered javascript function called before the rendering.
  29615. * This function is passed the current mesh.
  29616. * Returns the Mesh.
  29617. */
  29618. Mesh.prototype.unregisterBeforeRender = function (func) {
  29619. this.onBeforeRenderObservable.removeCallback(func);
  29620. return this;
  29621. };
  29622. /**
  29623. * Registers for this mesh a javascript function called just after the rendering is complete.
  29624. * This function is passed the current mesh.
  29625. * Returns the Mesh.
  29626. */
  29627. Mesh.prototype.registerAfterRender = function (func) {
  29628. this.onAfterRenderObservable.add(func);
  29629. return this;
  29630. };
  29631. /**
  29632. * Disposes a previously registered javascript function called after the rendering.
  29633. * This function is passed the current mesh.
  29634. * Return the Mesh.
  29635. */
  29636. Mesh.prototype.unregisterAfterRender = function (func) {
  29637. this.onAfterRenderObservable.removeCallback(func);
  29638. return this;
  29639. };
  29640. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  29641. var scene = this.getScene();
  29642. this._batchCache.mustReturn = false;
  29643. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  29644. this._batchCache.visibleInstances[subMeshId] = null;
  29645. if (this._visibleInstances) {
  29646. var currentRenderId = scene.getRenderId();
  29647. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  29648. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  29649. var selfRenderId = this._renderId;
  29650. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  29651. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  29652. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  29653. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  29654. }
  29655. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  29656. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  29657. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  29658. this._batchCache.mustReturn = true;
  29659. return this._batchCache;
  29660. }
  29661. if (currentRenderId !== selfRenderId) {
  29662. this._batchCache.renderSelf[subMeshId] = false;
  29663. }
  29664. }
  29665. this._renderIdForInstances[subMeshId] = currentRenderId;
  29666. }
  29667. return this._batchCache;
  29668. };
  29669. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  29670. var visibleInstances = batch.visibleInstances[subMesh._id];
  29671. if (!visibleInstances) {
  29672. return this;
  29673. }
  29674. var matricesCount = visibleInstances.length + 1;
  29675. var bufferSize = matricesCount * 16 * 4;
  29676. var currentInstancesBufferSize = this._instancesBufferSize;
  29677. var instancesBuffer = this._instancesBuffer;
  29678. while (this._instancesBufferSize < bufferSize) {
  29679. this._instancesBufferSize *= 2;
  29680. }
  29681. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  29682. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  29683. }
  29684. var offset = 0;
  29685. var instancesCount = 0;
  29686. var world = this.getWorldMatrix();
  29687. if (batch.renderSelf[subMesh._id]) {
  29688. world.copyToArray(this._instancesData, offset);
  29689. offset += 16;
  29690. instancesCount++;
  29691. }
  29692. if (visibleInstances) {
  29693. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  29694. var instance = visibleInstances[instanceIndex];
  29695. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  29696. offset += 16;
  29697. instancesCount++;
  29698. }
  29699. }
  29700. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  29701. if (instancesBuffer) {
  29702. instancesBuffer.dispose();
  29703. }
  29704. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  29705. this._instancesBuffer = instancesBuffer;
  29706. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  29707. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  29708. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  29709. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  29710. }
  29711. else {
  29712. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  29713. }
  29714. this._bind(subMesh, effect, fillMode);
  29715. this._draw(subMesh, fillMode, instancesCount);
  29716. engine.unbindInstanceAttributes();
  29717. return this;
  29718. };
  29719. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  29720. var scene = this.getScene();
  29721. var engine = scene.getEngine();
  29722. if (hardwareInstancedRendering) {
  29723. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  29724. }
  29725. else {
  29726. if (batch.renderSelf[subMesh._id]) {
  29727. // Draw
  29728. if (onBeforeDraw) {
  29729. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  29730. }
  29731. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  29732. }
  29733. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  29734. if (visibleInstancesForSubMesh) {
  29735. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  29736. var instance = visibleInstancesForSubMesh[instanceIndex];
  29737. // World
  29738. var world = instance.getWorldMatrix();
  29739. if (onBeforeDraw) {
  29740. onBeforeDraw(true, world, effectiveMaterial);
  29741. }
  29742. // Draw
  29743. this._draw(subMesh, fillMode);
  29744. }
  29745. }
  29746. }
  29747. return this;
  29748. };
  29749. /**
  29750. * Triggers the draw call for the mesh.
  29751. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  29752. * Returns the Mesh.
  29753. */
  29754. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  29755. this.checkOcclusionQuery();
  29756. if (this._isOccluded) {
  29757. return this;
  29758. }
  29759. var scene = this.getScene();
  29760. // Managing instances
  29761. var batch = this._getInstancesRenderList(subMesh._id);
  29762. if (batch.mustReturn) {
  29763. return this;
  29764. }
  29765. // Checking geometry state
  29766. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29767. return this;
  29768. }
  29769. this.onBeforeRenderObservable.notifyObservers(this);
  29770. var engine = scene.getEngine();
  29771. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29772. // Material
  29773. var material = subMesh.getMaterial();
  29774. if (!material) {
  29775. return this;
  29776. }
  29777. this._effectiveMaterial = material;
  29778. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29779. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  29780. return this;
  29781. }
  29782. }
  29783. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  29784. return this;
  29785. }
  29786. // Alpha mode
  29787. if (enableAlphaMode) {
  29788. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  29789. }
  29790. // Outline - step 1
  29791. var savedDepthWrite = engine.getDepthWrite();
  29792. if (this.renderOutline) {
  29793. engine.setDepthWrite(false);
  29794. scene.getOutlineRenderer().render(subMesh, batch);
  29795. engine.setDepthWrite(savedDepthWrite);
  29796. }
  29797. var effect;
  29798. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29799. effect = subMesh.effect;
  29800. }
  29801. else {
  29802. effect = this._effectiveMaterial.getEffect();
  29803. }
  29804. if (!effect) {
  29805. return this;
  29806. }
  29807. var sideOrientation = this.overrideMaterialSideOrientation;
  29808. if (sideOrientation == null) {
  29809. sideOrientation = this._effectiveMaterial.sideOrientation;
  29810. if (this._getWorldMatrixDeterminant() < 0) {
  29811. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29812. }
  29813. }
  29814. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29815. if (this._effectiveMaterial.forceDepthWrite) {
  29816. engine.setDepthWrite(true);
  29817. }
  29818. // Bind
  29819. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29820. if (!hardwareInstancedRendering) {
  29821. this._bind(subMesh, effect, fillMode);
  29822. }
  29823. var world = this.getWorldMatrix();
  29824. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29825. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29826. }
  29827. else {
  29828. this._effectiveMaterial.bind(world, this);
  29829. }
  29830. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29831. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29832. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29833. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29834. }
  29835. // Draw
  29836. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29837. // Unbind
  29838. this._effectiveMaterial.unbind();
  29839. // Outline - step 2
  29840. if (this.renderOutline && savedDepthWrite) {
  29841. engine.setDepthWrite(true);
  29842. engine.setColorWrite(false);
  29843. scene.getOutlineRenderer().render(subMesh, batch);
  29844. engine.setColorWrite(true);
  29845. }
  29846. // Overlay
  29847. if (this.renderOverlay) {
  29848. var currentMode = engine.getAlphaMode();
  29849. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29850. scene.getOutlineRenderer().render(subMesh, batch, true);
  29851. engine.setAlphaMode(currentMode);
  29852. }
  29853. this.onAfterRenderObservable.notifyObservers(this);
  29854. return this;
  29855. };
  29856. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29857. if (isInstance && effectiveMaterial) {
  29858. effectiveMaterial.bindOnlyWorldMatrix(world);
  29859. }
  29860. };
  29861. /**
  29862. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29863. */
  29864. Mesh.prototype.getEmittedParticleSystems = function () {
  29865. var results = new Array();
  29866. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29867. var particleSystem = this.getScene().particleSystems[index];
  29868. if (particleSystem.emitter === this) {
  29869. results.push(particleSystem);
  29870. }
  29871. }
  29872. return results;
  29873. };
  29874. /**
  29875. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29876. */
  29877. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29878. var results = new Array();
  29879. var descendants = this.getDescendants();
  29880. descendants.push(this);
  29881. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29882. var particleSystem = this.getScene().particleSystems[index];
  29883. var emitter = particleSystem.emitter;
  29884. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29885. results.push(particleSystem);
  29886. }
  29887. }
  29888. return results;
  29889. };
  29890. Mesh.prototype._checkDelayState = function () {
  29891. var scene = this.getScene();
  29892. if (this._geometry) {
  29893. this._geometry.load(scene);
  29894. }
  29895. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29896. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29897. this._queueLoad(scene);
  29898. }
  29899. return this;
  29900. };
  29901. Mesh.prototype._queueLoad = function (scene) {
  29902. var _this = this;
  29903. scene._addPendingData(this);
  29904. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29905. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29906. if (data instanceof ArrayBuffer) {
  29907. _this._delayLoadingFunction(data, _this);
  29908. }
  29909. else {
  29910. _this._delayLoadingFunction(JSON.parse(data), _this);
  29911. }
  29912. _this.instances.forEach(function (instance) {
  29913. instance._syncSubMeshes();
  29914. });
  29915. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29916. scene._removePendingData(_this);
  29917. }, function () { }, scene.database, getBinaryData);
  29918. return this;
  29919. };
  29920. /**
  29921. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29922. */
  29923. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29924. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29925. return false;
  29926. }
  29927. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29928. return false;
  29929. }
  29930. this._checkDelayState();
  29931. return true;
  29932. };
  29933. /**
  29934. * Sets the mesh material by the material or multiMaterial `id` property.
  29935. * The material `id` is a string identifying the material or the multiMaterial.
  29936. * This method returns the Mesh.
  29937. */
  29938. Mesh.prototype.setMaterialByID = function (id) {
  29939. var materials = this.getScene().materials;
  29940. var index;
  29941. for (index = materials.length - 1; index > -1; index--) {
  29942. if (materials[index].id === id) {
  29943. this.material = materials[index];
  29944. return this;
  29945. }
  29946. }
  29947. // Multi
  29948. var multiMaterials = this.getScene().multiMaterials;
  29949. for (index = multiMaterials.length - 1; index > -1; index--) {
  29950. if (multiMaterials[index].id === id) {
  29951. this.material = multiMaterials[index];
  29952. return this;
  29953. }
  29954. }
  29955. return this;
  29956. };
  29957. /**
  29958. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29959. */
  29960. Mesh.prototype.getAnimatables = function () {
  29961. var results = new Array();
  29962. if (this.material) {
  29963. results.push(this.material);
  29964. }
  29965. if (this.skeleton) {
  29966. results.push(this.skeleton);
  29967. }
  29968. return results;
  29969. };
  29970. /**
  29971. * Modifies the mesh geometry according to the passed transformation matrix.
  29972. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29973. * The mesh normals are modified accordingly the same transformation.
  29974. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29975. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29976. * Returns the Mesh.
  29977. */
  29978. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29979. // Position
  29980. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29981. return this;
  29982. }
  29983. var submeshes = this.subMeshes.splice(0);
  29984. this._resetPointsArrayCache();
  29985. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29986. var temp = new Array();
  29987. var index;
  29988. for (index = 0; index < data.length; index += 3) {
  29989. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29990. }
  29991. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29992. // Normals
  29993. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29994. return this;
  29995. }
  29996. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29997. temp = [];
  29998. for (index = 0; index < data.length; index += 3) {
  29999. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  30000. }
  30001. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  30002. // flip faces?
  30003. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  30004. this.flipFaces();
  30005. }
  30006. // Restore submeshes
  30007. this.releaseSubMeshes();
  30008. this.subMeshes = submeshes;
  30009. return this;
  30010. };
  30011. /**
  30012. * Modifies the mesh geometry according to its own current World Matrix.
  30013. * The mesh World Matrix is then reset.
  30014. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  30015. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  30016. * Note that, under the hood, this method sets a new VertexBuffer each call.
  30017. * Returns the Mesh.
  30018. */
  30019. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  30020. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  30021. this.scaling.copyFromFloats(1, 1, 1);
  30022. this.position.copyFromFloats(0, 0, 0);
  30023. this.rotation.copyFromFloats(0, 0, 0);
  30024. //only if quaternion is already set
  30025. if (this.rotationQuaternion) {
  30026. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  30027. }
  30028. this._worldMatrix = BABYLON.Matrix.Identity();
  30029. return this;
  30030. };
  30031. Object.defineProperty(Mesh.prototype, "_positions", {
  30032. // Cache
  30033. get: function () {
  30034. if (this._geometry) {
  30035. return this._geometry._positions;
  30036. }
  30037. return null;
  30038. },
  30039. enumerable: true,
  30040. configurable: true
  30041. });
  30042. Mesh.prototype._resetPointsArrayCache = function () {
  30043. if (this._geometry) {
  30044. this._geometry._resetPointsArrayCache();
  30045. }
  30046. return this;
  30047. };
  30048. Mesh.prototype._generatePointsArray = function () {
  30049. if (this._geometry) {
  30050. return this._geometry._generatePointsArray();
  30051. }
  30052. return false;
  30053. };
  30054. /**
  30055. * Returns a new Mesh object generated from the current mesh properties.
  30056. * This method must not get confused with createInstance().
  30057. * The parameter `name` is a string, the name given to the new mesh.
  30058. * The optional parameter `newParent` can be any Node object (default `null`).
  30059. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  30060. * 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.
  30061. */
  30062. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  30063. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30064. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  30065. };
  30066. /**
  30067. * Releases resources associated with this mesh.
  30068. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  30069. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  30070. */
  30071. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  30072. var _this = this;
  30073. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  30074. this.morphTargetManager = null;
  30075. if (this._geometry) {
  30076. this._geometry.releaseForMesh(this, true);
  30077. }
  30078. // Sources
  30079. var meshes = this.getScene().meshes;
  30080. meshes.forEach(function (abstractMesh) {
  30081. var mesh = abstractMesh;
  30082. if (mesh._source && mesh._source === _this) {
  30083. mesh._source = null;
  30084. }
  30085. });
  30086. this._source = null;
  30087. // Instances
  30088. if (this._instancesBuffer) {
  30089. this._instancesBuffer.dispose();
  30090. this._instancesBuffer = null;
  30091. }
  30092. while (this.instances.length) {
  30093. this.instances[0].dispose();
  30094. }
  30095. // Effect layers.
  30096. var effectLayers = this.getScene().effectLayers;
  30097. for (var i = 0; i < effectLayers.length; i++) {
  30098. var effectLayer = effectLayers[i];
  30099. if (effectLayer) {
  30100. effectLayer._disposeMesh(this);
  30101. }
  30102. }
  30103. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  30104. };
  30105. /**
  30106. * Modifies the mesh geometry according to a displacement map.
  30107. * 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.
  30108. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  30109. * This method returns nothing.
  30110. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  30111. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  30112. * 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.
  30113. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  30114. * The parameter `uvScale` is an optional vector2 used to scale UV.
  30115. *
  30116. * Returns the Mesh.
  30117. */
  30118. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  30119. var _this = this;
  30120. var scene = this.getScene();
  30121. var onload = function (img) {
  30122. // Getting height map data
  30123. var canvas = document.createElement("canvas");
  30124. var context = canvas.getContext("2d");
  30125. var heightMapWidth = img.width;
  30126. var heightMapHeight = img.height;
  30127. canvas.width = heightMapWidth;
  30128. canvas.height = heightMapHeight;
  30129. context.drawImage(img, 0, 0);
  30130. // Create VertexData from map data
  30131. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  30132. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  30133. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  30134. //execute success callback, if set
  30135. if (onSuccess) {
  30136. onSuccess(_this);
  30137. }
  30138. };
  30139. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  30140. return this;
  30141. };
  30142. /**
  30143. * Modifies the mesh geometry according to a displacementMap buffer.
  30144. * 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.
  30145. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  30146. * This method returns nothing.
  30147. * 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.
  30148. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  30149. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  30150. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  30151. * The parameter `uvScale` is an optional vector2 used to scale UV.
  30152. *
  30153. * Returns the Mesh.
  30154. */
  30155. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  30156. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  30157. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  30158. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30159. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  30160. return this;
  30161. }
  30162. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30163. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30164. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30165. var position = BABYLON.Vector3.Zero();
  30166. var normal = BABYLON.Vector3.Zero();
  30167. var uv = BABYLON.Vector2.Zero();
  30168. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  30169. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  30170. for (var index = 0; index < positions.length; index += 3) {
  30171. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  30172. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  30173. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  30174. // Compute height
  30175. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  30176. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  30177. var pos = (u + v * heightMapWidth) * 4;
  30178. var r = buffer[pos] / 255.0;
  30179. var g = buffer[pos + 1] / 255.0;
  30180. var b = buffer[pos + 2] / 255.0;
  30181. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  30182. normal.normalize();
  30183. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  30184. position = position.add(normal);
  30185. position.toArray(positions, index);
  30186. }
  30187. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  30188. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  30189. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  30190. return this;
  30191. };
  30192. /**
  30193. * Modify the mesh to get a flat shading rendering.
  30194. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  30195. * This method returns the Mesh.
  30196. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  30197. */
  30198. Mesh.prototype.convertToFlatShadedMesh = function () {
  30199. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  30200. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  30201. var kinds = this.getVerticesDataKinds();
  30202. var vbs = {};
  30203. var data = {};
  30204. var newdata = {};
  30205. var updatableNormals = false;
  30206. var kindIndex;
  30207. var kind;
  30208. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30209. kind = kinds[kindIndex];
  30210. var vertexBuffer = this.getVertexBuffer(kind);
  30211. if (kind === BABYLON.VertexBuffer.NormalKind) {
  30212. updatableNormals = vertexBuffer.isUpdatable();
  30213. kinds.splice(kindIndex, 1);
  30214. kindIndex--;
  30215. continue;
  30216. }
  30217. vbs[kind] = vertexBuffer;
  30218. data[kind] = vbs[kind].getData();
  30219. newdata[kind] = [];
  30220. }
  30221. // Save previous submeshes
  30222. var previousSubmeshes = this.subMeshes.slice(0);
  30223. var indices = this.getIndices();
  30224. var totalIndices = this.getTotalIndices();
  30225. // Generating unique vertices per face
  30226. var index;
  30227. for (index = 0; index < totalIndices; index++) {
  30228. var vertexIndex = indices[index];
  30229. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30230. kind = kinds[kindIndex];
  30231. var stride = vbs[kind].getStrideSize();
  30232. for (var offset = 0; offset < stride; offset++) {
  30233. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  30234. }
  30235. }
  30236. }
  30237. // Updating faces & normal
  30238. var normals = [];
  30239. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  30240. for (index = 0; index < totalIndices; index += 3) {
  30241. indices[index] = index;
  30242. indices[index + 1] = index + 1;
  30243. indices[index + 2] = index + 2;
  30244. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  30245. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  30246. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  30247. var p1p2 = p1.subtract(p2);
  30248. var p3p2 = p3.subtract(p2);
  30249. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  30250. // Store same normals for every vertex
  30251. for (var localIndex = 0; localIndex < 3; localIndex++) {
  30252. normals.push(normal.x);
  30253. normals.push(normal.y);
  30254. normals.push(normal.z);
  30255. }
  30256. }
  30257. this.setIndices(indices);
  30258. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  30259. // Updating vertex buffers
  30260. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30261. kind = kinds[kindIndex];
  30262. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  30263. }
  30264. // Updating submeshes
  30265. this.releaseSubMeshes();
  30266. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  30267. var previousOne = previousSubmeshes[submeshIndex];
  30268. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  30269. }
  30270. this.synchronizeInstances();
  30271. return this;
  30272. };
  30273. /**
  30274. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  30275. * In other words, more vertices, no more indices and a single bigger VBO.
  30276. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  30277. * Returns the Mesh.
  30278. */
  30279. Mesh.prototype.convertToUnIndexedMesh = function () {
  30280. /// <summary>Remove indices by unfolding faces into buffers</summary>
  30281. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  30282. var kinds = this.getVerticesDataKinds();
  30283. var vbs = {};
  30284. var data = {};
  30285. var newdata = {};
  30286. var kindIndex;
  30287. var kind;
  30288. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30289. kind = kinds[kindIndex];
  30290. var vertexBuffer = this.getVertexBuffer(kind);
  30291. vbs[kind] = vertexBuffer;
  30292. data[kind] = vbs[kind].getData();
  30293. newdata[kind] = [];
  30294. }
  30295. // Save previous submeshes
  30296. var previousSubmeshes = this.subMeshes.slice(0);
  30297. var indices = this.getIndices();
  30298. var totalIndices = this.getTotalIndices();
  30299. // Generating unique vertices per face
  30300. var index;
  30301. for (index = 0; index < totalIndices; index++) {
  30302. var vertexIndex = indices[index];
  30303. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30304. kind = kinds[kindIndex];
  30305. var stride = vbs[kind].getStrideSize();
  30306. for (var offset = 0; offset < stride; offset++) {
  30307. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  30308. }
  30309. }
  30310. }
  30311. // Updating indices
  30312. for (index = 0; index < totalIndices; index += 3) {
  30313. indices[index] = index;
  30314. indices[index + 1] = index + 1;
  30315. indices[index + 2] = index + 2;
  30316. }
  30317. this.setIndices(indices);
  30318. // Updating vertex buffers
  30319. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  30320. kind = kinds[kindIndex];
  30321. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  30322. }
  30323. // Updating submeshes
  30324. this.releaseSubMeshes();
  30325. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  30326. var previousOne = previousSubmeshes[submeshIndex];
  30327. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  30328. }
  30329. this._unIndexed = true;
  30330. this.synchronizeInstances();
  30331. return this;
  30332. };
  30333. /**
  30334. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  30335. * This method returns the Mesh.
  30336. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  30337. */
  30338. Mesh.prototype.flipFaces = function (flipNormals) {
  30339. if (flipNormals === void 0) { flipNormals = false; }
  30340. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  30341. var i;
  30342. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  30343. for (i = 0; i < vertex_data.normals.length; i++) {
  30344. vertex_data.normals[i] *= -1;
  30345. }
  30346. }
  30347. if (vertex_data.indices) {
  30348. var temp;
  30349. for (i = 0; i < vertex_data.indices.length; i += 3) {
  30350. // reassign indices
  30351. temp = vertex_data.indices[i + 1];
  30352. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  30353. vertex_data.indices[i + 2] = temp;
  30354. }
  30355. }
  30356. vertex_data.applyToMesh(this);
  30357. return this;
  30358. };
  30359. // Instances
  30360. /**
  30361. * Creates a new InstancedMesh object from the mesh model.
  30362. * An instance shares the same properties and the same material than its model.
  30363. * Only these properties of each instance can then be set individually :
  30364. * - position
  30365. * - rotation
  30366. * - rotationQuaternion
  30367. * - setPivotMatrix
  30368. * - scaling
  30369. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  30370. * Warning : this method is not supported for Line mesh and LineSystem
  30371. */
  30372. Mesh.prototype.createInstance = function (name) {
  30373. return new BABYLON.InstancedMesh(name, this);
  30374. };
  30375. /**
  30376. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  30377. * After this call, all the mesh instances have the same submeshes than the current mesh.
  30378. * This method returns the Mesh.
  30379. */
  30380. Mesh.prototype.synchronizeInstances = function () {
  30381. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  30382. var instance = this.instances[instanceIndex];
  30383. instance._syncSubMeshes();
  30384. }
  30385. return this;
  30386. };
  30387. /**
  30388. * Simplify the mesh according to the given array of settings.
  30389. * Function will return immediately and will simplify async. It returns the Mesh.
  30390. * @param settings a collection of simplification settings.
  30391. * @param parallelProcessing should all levels calculate parallel or one after the other.
  30392. * @param type the type of simplification to run.
  30393. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  30394. */
  30395. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  30396. if (parallelProcessing === void 0) { parallelProcessing = true; }
  30397. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  30398. this.getScene().simplificationQueue.addTask({
  30399. settings: settings,
  30400. parallelProcessing: parallelProcessing,
  30401. mesh: this,
  30402. simplificationType: simplificationType,
  30403. successCallback: successCallback
  30404. });
  30405. return this;
  30406. };
  30407. /**
  30408. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  30409. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  30410. * This should be used together with the simplification to avoid disappearing triangles.
  30411. * Returns the Mesh.
  30412. * @param successCallback an optional success callback to be called after the optimization finished.
  30413. */
  30414. Mesh.prototype.optimizeIndices = function (successCallback) {
  30415. var _this = this;
  30416. var indices = this.getIndices();
  30417. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30418. if (!positions || !indices) {
  30419. return this;
  30420. }
  30421. var vectorPositions = new Array();
  30422. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  30423. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  30424. }
  30425. var dupes = new Array();
  30426. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  30427. var realPos = vectorPositions.length - 1 - iteration;
  30428. var testedPosition = vectorPositions[realPos];
  30429. for (var j = 0; j < realPos; ++j) {
  30430. var againstPosition = vectorPositions[j];
  30431. if (testedPosition.equals(againstPosition)) {
  30432. dupes[realPos] = j;
  30433. break;
  30434. }
  30435. }
  30436. }, function () {
  30437. for (var i = 0; i < indices.length; ++i) {
  30438. indices[i] = dupes[indices[i]] || indices[i];
  30439. }
  30440. //indices are now reordered
  30441. var originalSubMeshes = _this.subMeshes.slice(0);
  30442. _this.setIndices(indices);
  30443. _this.subMeshes = originalSubMeshes;
  30444. if (successCallback) {
  30445. successCallback(_this);
  30446. }
  30447. });
  30448. return this;
  30449. };
  30450. Mesh.prototype.serialize = function (serializationObject) {
  30451. serializationObject.name = this.name;
  30452. serializationObject.id = this.id;
  30453. serializationObject.type = this.getClassName();
  30454. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30455. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30456. }
  30457. serializationObject.position = this.position.asArray();
  30458. if (this.rotationQuaternion) {
  30459. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  30460. }
  30461. else if (this.rotation) {
  30462. serializationObject.rotation = this.rotation.asArray();
  30463. }
  30464. serializationObject.scaling = this.scaling.asArray();
  30465. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  30466. serializationObject.isEnabled = this.isEnabled(false);
  30467. serializationObject.isVisible = this.isVisible;
  30468. serializationObject.infiniteDistance = this.infiniteDistance;
  30469. serializationObject.pickable = this.isPickable;
  30470. serializationObject.receiveShadows = this.receiveShadows;
  30471. serializationObject.billboardMode = this.billboardMode;
  30472. serializationObject.visibility = this.visibility;
  30473. serializationObject.checkCollisions = this.checkCollisions;
  30474. serializationObject.isBlocker = this.isBlocker;
  30475. // Parent
  30476. if (this.parent) {
  30477. serializationObject.parentId = this.parent.id;
  30478. }
  30479. // Geometry
  30480. serializationObject.isUnIndexed = this.isUnIndexed;
  30481. var geometry = this._geometry;
  30482. if (geometry) {
  30483. var geometryId = geometry.id;
  30484. serializationObject.geometryId = geometryId;
  30485. // SubMeshes
  30486. serializationObject.subMeshes = [];
  30487. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  30488. var subMesh = this.subMeshes[subIndex];
  30489. serializationObject.subMeshes.push({
  30490. materialIndex: subMesh.materialIndex,
  30491. verticesStart: subMesh.verticesStart,
  30492. verticesCount: subMesh.verticesCount,
  30493. indexStart: subMesh.indexStart,
  30494. indexCount: subMesh.indexCount
  30495. });
  30496. }
  30497. }
  30498. // Material
  30499. if (this.material) {
  30500. serializationObject.materialId = this.material.id;
  30501. }
  30502. else {
  30503. this.material = null;
  30504. }
  30505. // Morph targets
  30506. if (this.morphTargetManager) {
  30507. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  30508. }
  30509. // Skeleton
  30510. if (this.skeleton) {
  30511. serializationObject.skeletonId = this.skeleton.id;
  30512. }
  30513. // Physics
  30514. //TODO implement correct serialization for physics impostors.
  30515. var impostor = this.getPhysicsImpostor();
  30516. if (impostor) {
  30517. serializationObject.physicsMass = impostor.getParam("mass");
  30518. serializationObject.physicsFriction = impostor.getParam("friction");
  30519. serializationObject.physicsRestitution = impostor.getParam("mass");
  30520. serializationObject.physicsImpostor = impostor.type;
  30521. }
  30522. // Metadata
  30523. if (this.metadata) {
  30524. serializationObject.metadata = this.metadata;
  30525. }
  30526. // Instances
  30527. serializationObject.instances = [];
  30528. for (var index = 0; index < this.instances.length; index++) {
  30529. var instance = this.instances[index];
  30530. var serializationInstance = {
  30531. name: instance.name,
  30532. id: instance.id,
  30533. position: instance.position.asArray(),
  30534. scaling: instance.scaling.asArray()
  30535. };
  30536. if (instance.rotationQuaternion) {
  30537. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  30538. }
  30539. else if (instance.rotation) {
  30540. serializationInstance.rotation = instance.rotation.asArray();
  30541. }
  30542. serializationObject.instances.push(serializationInstance);
  30543. // Animations
  30544. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  30545. serializationInstance.ranges = instance.serializeAnimationRanges();
  30546. }
  30547. //
  30548. // Animations
  30549. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30550. serializationObject.ranges = this.serializeAnimationRanges();
  30551. // Layer mask
  30552. serializationObject.layerMask = this.layerMask;
  30553. // Alpha
  30554. serializationObject.alphaIndex = this.alphaIndex;
  30555. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  30556. // Overlay
  30557. serializationObject.overlayAlpha = this.overlayAlpha;
  30558. serializationObject.overlayColor = this.overlayColor.asArray();
  30559. serializationObject.renderOverlay = this.renderOverlay;
  30560. // Fog
  30561. serializationObject.applyFog = this.applyFog;
  30562. // Action Manager
  30563. if (this.actionManager) {
  30564. serializationObject.actions = this.actionManager.serialize(this.name);
  30565. }
  30566. };
  30567. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  30568. if (!this.geometry) {
  30569. return;
  30570. }
  30571. this._markSubMeshesAsAttributesDirty();
  30572. var morphTargetManager = this._morphTargetManager;
  30573. if (morphTargetManager && morphTargetManager.vertexCount) {
  30574. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  30575. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  30576. this.morphTargetManager = null;
  30577. return;
  30578. }
  30579. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  30580. var morphTarget = morphTargetManager.getActiveTarget(index);
  30581. var positions = morphTarget.getPositions();
  30582. if (!positions) {
  30583. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  30584. return;
  30585. }
  30586. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  30587. var normals = morphTarget.getNormals();
  30588. if (normals) {
  30589. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  30590. }
  30591. var tangents = morphTarget.getTangents();
  30592. if (tangents) {
  30593. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  30594. }
  30595. }
  30596. }
  30597. else {
  30598. var index = 0;
  30599. // Positions
  30600. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  30601. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  30602. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  30603. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  30604. }
  30605. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  30606. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  30607. }
  30608. index++;
  30609. }
  30610. }
  30611. };
  30612. // Statics
  30613. /**
  30614. * Returns a new Mesh object parsed from the source provided.
  30615. * The parameter `parsedMesh` is the source.
  30616. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  30617. */
  30618. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  30619. var mesh;
  30620. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  30621. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  30622. }
  30623. else {
  30624. mesh = new Mesh(parsedMesh.name, scene);
  30625. }
  30626. mesh.id = parsedMesh.id;
  30627. if (BABYLON.Tags) {
  30628. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  30629. }
  30630. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  30631. if (parsedMesh.metadata !== undefined) {
  30632. mesh.metadata = parsedMesh.metadata;
  30633. }
  30634. if (parsedMesh.rotationQuaternion) {
  30635. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  30636. }
  30637. else if (parsedMesh.rotation) {
  30638. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  30639. }
  30640. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  30641. if (parsedMesh.localMatrix) {
  30642. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  30643. }
  30644. else if (parsedMesh.pivotMatrix) {
  30645. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  30646. }
  30647. mesh.setEnabled(parsedMesh.isEnabled);
  30648. mesh.isVisible = parsedMesh.isVisible;
  30649. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  30650. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  30651. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  30652. if (parsedMesh.applyFog !== undefined) {
  30653. mesh.applyFog = parsedMesh.applyFog;
  30654. }
  30655. if (parsedMesh.pickable !== undefined) {
  30656. mesh.isPickable = parsedMesh.pickable;
  30657. }
  30658. if (parsedMesh.alphaIndex !== undefined) {
  30659. mesh.alphaIndex = parsedMesh.alphaIndex;
  30660. }
  30661. mesh.receiveShadows = parsedMesh.receiveShadows;
  30662. mesh.billboardMode = parsedMesh.billboardMode;
  30663. if (parsedMesh.visibility !== undefined) {
  30664. mesh.visibility = parsedMesh.visibility;
  30665. }
  30666. mesh.checkCollisions = parsedMesh.checkCollisions;
  30667. if (parsedMesh.isBlocker !== undefined) {
  30668. mesh.isBlocker = parsedMesh.isBlocker;
  30669. }
  30670. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  30671. // freezeWorldMatrix
  30672. if (parsedMesh.freezeWorldMatrix) {
  30673. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  30674. }
  30675. // Parent
  30676. if (parsedMesh.parentId) {
  30677. mesh._waitingParentId = parsedMesh.parentId;
  30678. }
  30679. // Actions
  30680. if (parsedMesh.actions !== undefined) {
  30681. mesh._waitingActions = parsedMesh.actions;
  30682. }
  30683. // Overlay
  30684. if (parsedMesh.overlayAlpha !== undefined) {
  30685. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  30686. }
  30687. if (parsedMesh.overlayColor !== undefined) {
  30688. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  30689. }
  30690. if (parsedMesh.renderOverlay !== undefined) {
  30691. mesh.renderOverlay = parsedMesh.renderOverlay;
  30692. }
  30693. // Geometry
  30694. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  30695. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  30696. if (parsedMesh.delayLoadingFile) {
  30697. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30698. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  30699. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  30700. if (parsedMesh._binaryInfo) {
  30701. mesh._binaryInfo = parsedMesh._binaryInfo;
  30702. }
  30703. mesh._delayInfo = [];
  30704. if (parsedMesh.hasUVs) {
  30705. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  30706. }
  30707. if (parsedMesh.hasUVs2) {
  30708. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  30709. }
  30710. if (parsedMesh.hasUVs3) {
  30711. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  30712. }
  30713. if (parsedMesh.hasUVs4) {
  30714. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  30715. }
  30716. if (parsedMesh.hasUVs5) {
  30717. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  30718. }
  30719. if (parsedMesh.hasUVs6) {
  30720. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  30721. }
  30722. if (parsedMesh.hasColors) {
  30723. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  30724. }
  30725. if (parsedMesh.hasMatricesIndices) {
  30726. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30727. }
  30728. if (parsedMesh.hasMatricesWeights) {
  30729. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30730. }
  30731. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  30732. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  30733. mesh._checkDelayState();
  30734. }
  30735. }
  30736. else {
  30737. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  30738. }
  30739. // Material
  30740. if (parsedMesh.materialId) {
  30741. mesh.setMaterialByID(parsedMesh.materialId);
  30742. }
  30743. else {
  30744. mesh.material = null;
  30745. }
  30746. // Morph targets
  30747. if (parsedMesh.morphTargetManagerId > -1) {
  30748. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  30749. }
  30750. // Skeleton
  30751. if (parsedMesh.skeletonId > -1) {
  30752. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  30753. if (parsedMesh.numBoneInfluencers) {
  30754. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  30755. }
  30756. }
  30757. // Animations
  30758. if (parsedMesh.animations) {
  30759. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30760. var parsedAnimation = parsedMesh.animations[animationIndex];
  30761. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30762. }
  30763. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  30764. }
  30765. if (parsedMesh.autoAnimate) {
  30766. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  30767. }
  30768. // Layer Mask
  30769. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  30770. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  30771. }
  30772. else {
  30773. mesh.layerMask = 0x0FFFFFFF;
  30774. }
  30775. // Physics
  30776. if (parsedMesh.physicsImpostor) {
  30777. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  30778. mass: parsedMesh.physicsMass,
  30779. friction: parsedMesh.physicsFriction,
  30780. restitution: parsedMesh.physicsRestitution
  30781. }, scene);
  30782. }
  30783. // Instances
  30784. if (parsedMesh.instances) {
  30785. for (var index = 0; index < parsedMesh.instances.length; index++) {
  30786. var parsedInstance = parsedMesh.instances[index];
  30787. var instance = mesh.createInstance(parsedInstance.name);
  30788. if (parsedInstance.id) {
  30789. instance.id = parsedInstance.id;
  30790. }
  30791. if (BABYLON.Tags) {
  30792. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30793. }
  30794. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30795. if (parsedInstance.parentId) {
  30796. instance._waitingParentId = parsedInstance.parentId;
  30797. }
  30798. if (parsedInstance.rotationQuaternion) {
  30799. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30800. }
  30801. else if (parsedInstance.rotation) {
  30802. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30803. }
  30804. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30805. instance.checkCollisions = mesh.checkCollisions;
  30806. if (parsedMesh.animations) {
  30807. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30808. parsedAnimation = parsedMesh.animations[animationIndex];
  30809. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30810. }
  30811. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30812. }
  30813. }
  30814. }
  30815. return mesh;
  30816. };
  30817. /**
  30818. * Creates a ribbon mesh.
  30819. * Please consider using the same method from the MeshBuilder class instead.
  30820. * 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.
  30821. *
  30822. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30823. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30824. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30825. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30826. * 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.
  30827. * 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.
  30828. * 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
  30829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30830. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30831. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30832. */
  30833. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30834. if (closeArray === void 0) { closeArray = false; }
  30835. if (updatable === void 0) { updatable = false; }
  30836. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30837. pathArray: pathArray,
  30838. closeArray: closeArray,
  30839. closePath: closePath,
  30840. offset: offset,
  30841. updatable: updatable,
  30842. sideOrientation: sideOrientation,
  30843. instance: instance
  30844. }, scene);
  30845. };
  30846. /**
  30847. * Creates a plane polygonal mesh. By default, this is a disc.
  30848. * Please consider using the same method from the MeshBuilder class instead.
  30849. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30850. * 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.
  30851. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30852. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30854. */
  30855. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30856. if (scene === void 0) { scene = null; }
  30857. var options = {
  30858. radius: radius,
  30859. tessellation: tessellation,
  30860. sideOrientation: sideOrientation,
  30861. updatable: updatable
  30862. };
  30863. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30864. };
  30865. /**
  30866. * Creates a box mesh.
  30867. * Please consider using the same method from the MeshBuilder class instead.
  30868. * The parameter `size` sets the size (float) of each box side (default 1).
  30869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30870. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30872. */
  30873. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30874. if (scene === void 0) { scene = null; }
  30875. var options = {
  30876. size: size,
  30877. sideOrientation: sideOrientation,
  30878. updatable: updatable
  30879. };
  30880. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30881. };
  30882. /**
  30883. * Creates a sphere mesh.
  30884. * Please consider using the same method from the MeshBuilder class instead.
  30885. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30886. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30887. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30888. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30889. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30890. */
  30891. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30892. var options = {
  30893. segments: segments,
  30894. diameterX: diameter,
  30895. diameterY: diameter,
  30896. diameterZ: diameter,
  30897. sideOrientation: sideOrientation,
  30898. updatable: updatable
  30899. };
  30900. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30901. };
  30902. /**
  30903. * Creates a cylinder or a cone mesh.
  30904. * Please consider using the same method from the MeshBuilder class instead.
  30905. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30906. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30907. * 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.
  30908. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30909. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30910. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30911. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30912. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30913. */
  30914. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30915. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30916. if (scene !== undefined) {
  30917. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30918. updatable = scene;
  30919. }
  30920. scene = subdivisions;
  30921. subdivisions = 1;
  30922. }
  30923. var options = {
  30924. height: height,
  30925. diameterTop: diameterTop,
  30926. diameterBottom: diameterBottom,
  30927. tessellation: tessellation,
  30928. subdivisions: subdivisions,
  30929. sideOrientation: sideOrientation,
  30930. updatable: updatable
  30931. };
  30932. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30933. };
  30934. // Torus (Code from SharpDX.org)
  30935. /**
  30936. * Creates a torus mesh.
  30937. * Please consider using the same method from the MeshBuilder class instead.
  30938. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30939. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30940. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30944. */
  30945. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30946. var options = {
  30947. diameter: diameter,
  30948. thickness: thickness,
  30949. tessellation: tessellation,
  30950. sideOrientation: sideOrientation,
  30951. updatable: updatable
  30952. };
  30953. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30954. };
  30955. /**
  30956. * Creates a torus knot mesh.
  30957. * Please consider using the same method from the MeshBuilder class instead.
  30958. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30959. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30960. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30961. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30965. */
  30966. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30967. var options = {
  30968. radius: radius,
  30969. tube: tube,
  30970. radialSegments: radialSegments,
  30971. tubularSegments: tubularSegments,
  30972. p: p,
  30973. q: q,
  30974. sideOrientation: sideOrientation,
  30975. updatable: updatable
  30976. };
  30977. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30978. };
  30979. /**
  30980. * Creates a line mesh.
  30981. * Please consider using the same method from the MeshBuilder class instead.
  30982. * 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.
  30983. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30984. * The parameter `points` is an array successive Vector3.
  30985. * 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
  30986. * When updating an instance, remember that only point positions can change, not the number of points.
  30987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30988. */
  30989. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30990. if (scene === void 0) { scene = null; }
  30991. if (updatable === void 0) { updatable = false; }
  30992. if (instance === void 0) { instance = null; }
  30993. var options = {
  30994. points: points,
  30995. updatable: updatable,
  30996. instance: instance
  30997. };
  30998. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30999. };
  31000. /**
  31001. * Creates a dashed line mesh.
  31002. * Please consider using the same method from the MeshBuilder class instead.
  31003. * 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.
  31004. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  31005. * The parameter `points` is an array successive Vector3.
  31006. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  31007. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  31008. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  31009. * 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
  31010. * When updating an instance, remember that only point positions can change, not the number of points.
  31011. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31012. */
  31013. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  31014. if (scene === void 0) { scene = null; }
  31015. var options = {
  31016. points: points,
  31017. dashSize: dashSize,
  31018. gapSize: gapSize,
  31019. dashNb: dashNb,
  31020. updatable: updatable,
  31021. instance: instance
  31022. };
  31023. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  31024. };
  31025. /**
  31026. * Creates a polygon mesh.
  31027. * Please consider using the same method from the MeshBuilder class instead.
  31028. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  31029. * 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.
  31030. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31032. * Remember you can only change the shape positions, not their number when updating a polygon.
  31033. */
  31034. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  31035. var options = {
  31036. shape: shape,
  31037. holes: holes,
  31038. updatable: updatable,
  31039. sideOrientation: sideOrientation
  31040. };
  31041. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  31042. };
  31043. /**
  31044. * Creates an extruded polygon mesh, with depth in the Y direction.
  31045. * Please consider using the same method from the MeshBuilder class instead.
  31046. */
  31047. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  31048. var options = {
  31049. shape: shape,
  31050. holes: holes,
  31051. depth: depth,
  31052. updatable: updatable,
  31053. sideOrientation: sideOrientation
  31054. };
  31055. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  31056. };
  31057. /**
  31058. * Creates an extruded shape mesh.
  31059. * 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.
  31060. * Please consider using the same method from the MeshBuilder class instead.
  31061. *
  31062. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  31063. * 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
  31064. * extruded along the Z axis.
  31065. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  31066. * 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.
  31067. * The parameter `scale` (float, default 1) is the value to scale the shape.
  31068. * 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
  31069. * 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
  31070. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  31071. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31073. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31074. */
  31075. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  31076. if (scene === void 0) { scene = null; }
  31077. var options = {
  31078. shape: shape,
  31079. path: path,
  31080. scale: scale,
  31081. rotation: rotation,
  31082. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  31083. sideOrientation: sideOrientation,
  31084. instance: instance,
  31085. updatable: updatable
  31086. };
  31087. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  31088. };
  31089. /**
  31090. * Creates an custom extruded shape mesh.
  31091. * 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.
  31092. * Please consider using the same method from the MeshBuilder class instead.
  31093. *
  31094. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  31095. * 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
  31096. * extruded along the Z axis.
  31097. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  31098. * 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
  31099. * and the distance of this point from the begining of the path :
  31100. * ```javascript
  31101. * var rotationFunction = function(i, distance) {
  31102. * // do things
  31103. * return rotationValue; }
  31104. * ```
  31105. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  31106. * 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
  31107. * and the distance of this point from the begining of the path :
  31108. * ```javascript
  31109. * var scaleFunction = function(i, distance) {
  31110. * // do things
  31111. * return scaleValue;}
  31112. * ```
  31113. * It must returns a float value that will be the scale value applied to the shape on each path point.
  31114. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  31115. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  31116. * 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
  31117. * 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
  31118. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  31119. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31121. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31122. */
  31123. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  31124. var options = {
  31125. shape: shape,
  31126. path: path,
  31127. scaleFunction: scaleFunction,
  31128. rotationFunction: rotationFunction,
  31129. ribbonCloseArray: ribbonCloseArray,
  31130. ribbonClosePath: ribbonClosePath,
  31131. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  31132. sideOrientation: sideOrientation,
  31133. instance: instance,
  31134. updatable: updatable
  31135. };
  31136. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  31137. };
  31138. /**
  31139. * Creates lathe mesh.
  31140. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  31141. * Please consider using the same method from the MeshBuilder class instead.
  31142. * 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
  31143. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  31144. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  31145. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  31146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31147. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31148. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31149. */
  31150. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  31151. var options = {
  31152. shape: shape,
  31153. radius: radius,
  31154. tessellation: tessellation,
  31155. sideOrientation: sideOrientation,
  31156. updatable: updatable
  31157. };
  31158. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  31159. };
  31160. /**
  31161. * Creates a plane mesh.
  31162. * Please consider using the same method from the MeshBuilder class instead.
  31163. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  31164. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31165. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31167. */
  31168. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  31169. var options = {
  31170. size: size,
  31171. width: size,
  31172. height: size,
  31173. sideOrientation: sideOrientation,
  31174. updatable: updatable
  31175. };
  31176. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  31177. };
  31178. /**
  31179. * Creates a ground mesh.
  31180. * Please consider using the same method from the MeshBuilder class instead.
  31181. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  31182. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  31183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31184. */
  31185. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  31186. var options = {
  31187. width: width,
  31188. height: height,
  31189. subdivisions: subdivisions,
  31190. updatable: updatable
  31191. };
  31192. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  31193. };
  31194. /**
  31195. * Creates a tiled ground mesh.
  31196. * Please consider using the same method from the MeshBuilder class instead.
  31197. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  31198. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  31199. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  31200. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  31201. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  31202. * numbers of subdivisions on the ground width and height of each tile.
  31203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31204. */
  31205. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  31206. var options = {
  31207. xmin: xmin,
  31208. zmin: zmin,
  31209. xmax: xmax,
  31210. zmax: zmax,
  31211. subdivisions: subdivisions,
  31212. precision: precision,
  31213. updatable: updatable
  31214. };
  31215. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  31216. };
  31217. /**
  31218. * Creates a ground mesh from a height map.
  31219. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  31220. * Please consider using the same method from the MeshBuilder class instead.
  31221. * The parameter `url` sets the URL of the height map image resource.
  31222. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  31223. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  31224. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  31225. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  31226. * 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).
  31227. * This function is passed the newly built mesh :
  31228. * ```javascript
  31229. * function(mesh) { // do things
  31230. * return; }
  31231. * ```
  31232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31233. */
  31234. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  31235. var options = {
  31236. width: width,
  31237. height: height,
  31238. subdivisions: subdivisions,
  31239. minHeight: minHeight,
  31240. maxHeight: maxHeight,
  31241. updatable: updatable,
  31242. onReady: onReady
  31243. };
  31244. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  31245. };
  31246. /**
  31247. * Creates a tube mesh.
  31248. * 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.
  31249. * Please consider using the same method from the MeshBuilder class instead.
  31250. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  31251. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  31252. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  31253. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  31254. * 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.
  31255. * It must return a radius value (positive float) :
  31256. * ```javascript
  31257. * var radiusFunction = function(i, distance) {
  31258. * // do things
  31259. * return radius; }
  31260. * ```
  31261. * 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
  31262. * 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
  31263. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31264. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31266. */
  31267. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  31268. var options = {
  31269. path: path,
  31270. radius: radius,
  31271. tessellation: tessellation,
  31272. radiusFunction: radiusFunction,
  31273. arc: 1,
  31274. cap: cap,
  31275. updatable: updatable,
  31276. sideOrientation: sideOrientation,
  31277. instance: instance
  31278. };
  31279. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  31280. };
  31281. /**
  31282. * Creates a polyhedron mesh.
  31283. * Please consider using the same method from the MeshBuilder class instead.
  31284. * 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
  31285. * to choose the wanted type.
  31286. * The parameter `size` (positive float, default 1) sets the polygon size.
  31287. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  31288. * 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`.
  31289. * 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
  31290. * 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)`).
  31291. * 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
  31292. * 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.
  31293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31294. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31296. */
  31297. Mesh.CreatePolyhedron = function (name, options, scene) {
  31298. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  31299. };
  31300. /**
  31301. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  31302. * Please consider using the same method from the MeshBuilder class instead.
  31303. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  31304. * 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`).
  31305. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  31306. * 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.
  31307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  31308. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  31309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  31310. */
  31311. Mesh.CreateIcoSphere = function (name, options, scene) {
  31312. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  31313. };
  31314. /**
  31315. * Creates a decal mesh.
  31316. * Please consider using the same method from the MeshBuilder class instead.
  31317. * 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.
  31318. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  31319. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  31320. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  31321. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  31322. */
  31323. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  31324. var options = {
  31325. position: position,
  31326. normal: normal,
  31327. size: size,
  31328. angle: angle
  31329. };
  31330. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  31331. };
  31332. // Skeletons
  31333. /**
  31334. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  31335. */
  31336. Mesh.prototype.setPositionsForCPUSkinning = function () {
  31337. if (!this._sourcePositions) {
  31338. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31339. if (!source) {
  31340. return this._sourcePositions;
  31341. }
  31342. this._sourcePositions = new Float32Array(source);
  31343. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31344. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  31345. }
  31346. }
  31347. return this._sourcePositions;
  31348. };
  31349. /**
  31350. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  31351. */
  31352. Mesh.prototype.setNormalsForCPUSkinning = function () {
  31353. if (!this._sourceNormals) {
  31354. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31355. if (!source) {
  31356. return this._sourceNormals;
  31357. }
  31358. this._sourceNormals = new Float32Array(source);
  31359. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31360. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  31361. }
  31362. }
  31363. return this._sourceNormals;
  31364. };
  31365. /**
  31366. * Updates the vertex buffer by applying transformation from the bones.
  31367. * Returns the Mesh.
  31368. *
  31369. * @param {skeleton} skeleton to apply
  31370. */
  31371. Mesh.prototype.applySkeleton = function (skeleton) {
  31372. if (!this.geometry) {
  31373. return this;
  31374. }
  31375. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  31376. return this;
  31377. }
  31378. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  31379. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31380. return this;
  31381. }
  31382. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31383. return this;
  31384. }
  31385. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31386. return this;
  31387. }
  31388. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31389. return this;
  31390. }
  31391. if (!this._sourcePositions) {
  31392. var submeshes = this.subMeshes.slice();
  31393. this.setPositionsForCPUSkinning();
  31394. this.subMeshes = submeshes;
  31395. }
  31396. if (!this._sourceNormals) {
  31397. this.setNormalsForCPUSkinning();
  31398. }
  31399. // positionsData checks for not being Float32Array will only pass at most once
  31400. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31401. if (!positionsData) {
  31402. return this;
  31403. }
  31404. if (!(positionsData instanceof Float32Array)) {
  31405. positionsData = new Float32Array(positionsData);
  31406. }
  31407. // normalsData checks for not being Float32Array will only pass at most once
  31408. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31409. if (!normalsData) {
  31410. return this;
  31411. }
  31412. if (!(normalsData instanceof Float32Array)) {
  31413. normalsData = new Float32Array(normalsData);
  31414. }
  31415. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31416. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31417. if (!matricesWeightsData || !matricesIndicesData) {
  31418. return this;
  31419. }
  31420. var needExtras = this.numBoneInfluencers > 4;
  31421. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31422. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31423. var skeletonMatrices = skeleton.getTransformMatrices(this);
  31424. var tempVector3 = BABYLON.Vector3.Zero();
  31425. var finalMatrix = new BABYLON.Matrix();
  31426. var tempMatrix = new BABYLON.Matrix();
  31427. var matWeightIdx = 0;
  31428. var inf;
  31429. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  31430. var weight;
  31431. for (inf = 0; inf < 4; inf++) {
  31432. weight = matricesWeightsData[matWeightIdx + inf];
  31433. if (weight > 0) {
  31434. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31435. finalMatrix.addToSelf(tempMatrix);
  31436. }
  31437. else
  31438. break;
  31439. }
  31440. if (needExtras) {
  31441. for (inf = 0; inf < 4; inf++) {
  31442. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31443. if (weight > 0) {
  31444. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31445. finalMatrix.addToSelf(tempMatrix);
  31446. }
  31447. else
  31448. break;
  31449. }
  31450. }
  31451. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  31452. tempVector3.toArray(positionsData, index);
  31453. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  31454. tempVector3.toArray(normalsData, index);
  31455. finalMatrix.reset();
  31456. }
  31457. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  31458. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  31459. return this;
  31460. };
  31461. // Tools
  31462. /**
  31463. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  31464. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  31465. */
  31466. Mesh.MinMax = function (meshes) {
  31467. var minVector = null;
  31468. var maxVector = null;
  31469. meshes.forEach(function (mesh, index, array) {
  31470. var boundingInfo = mesh.getBoundingInfo();
  31471. var boundingBox = boundingInfo.boundingBox;
  31472. if (!minVector || !maxVector) {
  31473. minVector = boundingBox.minimumWorld;
  31474. maxVector = boundingBox.maximumWorld;
  31475. }
  31476. else {
  31477. minVector.minimizeInPlace(boundingBox.minimumWorld);
  31478. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  31479. }
  31480. });
  31481. if (!minVector || !maxVector) {
  31482. return {
  31483. min: BABYLON.Vector3.Zero(),
  31484. max: BABYLON.Vector3.Zero()
  31485. };
  31486. }
  31487. return {
  31488. min: minVector,
  31489. max: maxVector
  31490. };
  31491. };
  31492. /**
  31493. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  31494. */
  31495. Mesh.Center = function (meshesOrMinMaxVector) {
  31496. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  31497. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  31498. };
  31499. /**
  31500. * Merge the array of meshes into a single mesh for performance reasons.
  31501. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  31502. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  31503. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  31504. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  31505. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  31506. */
  31507. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  31508. if (disposeSource === void 0) { disposeSource = true; }
  31509. var index;
  31510. if (!allow32BitsIndices) {
  31511. var totalVertices = 0;
  31512. // Counting vertices
  31513. for (index = 0; index < meshes.length; index++) {
  31514. if (meshes[index]) {
  31515. totalVertices += meshes[index].getTotalVertices();
  31516. if (totalVertices > 65536) {
  31517. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  31518. return null;
  31519. }
  31520. }
  31521. }
  31522. }
  31523. // Merge
  31524. var vertexData = null;
  31525. var otherVertexData;
  31526. var indiceArray = new Array();
  31527. var source = null;
  31528. for (index = 0; index < meshes.length; index++) {
  31529. if (meshes[index]) {
  31530. meshes[index].computeWorldMatrix(true);
  31531. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  31532. otherVertexData.transform(meshes[index].getWorldMatrix());
  31533. if (vertexData) {
  31534. vertexData.merge(otherVertexData);
  31535. }
  31536. else {
  31537. vertexData = otherVertexData;
  31538. source = meshes[index];
  31539. }
  31540. if (subdivideWithSubMeshes) {
  31541. indiceArray.push(meshes[index].getTotalIndices());
  31542. }
  31543. }
  31544. }
  31545. source = source;
  31546. if (!meshSubclass) {
  31547. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  31548. }
  31549. vertexData.applyToMesh(meshSubclass);
  31550. // Setting properties
  31551. meshSubclass.material = source.material;
  31552. meshSubclass.checkCollisions = source.checkCollisions;
  31553. // Cleaning
  31554. if (disposeSource) {
  31555. for (index = 0; index < meshes.length; index++) {
  31556. if (meshes[index]) {
  31557. meshes[index].dispose();
  31558. }
  31559. }
  31560. }
  31561. // Subdivide
  31562. if (subdivideWithSubMeshes) {
  31563. //-- Suppresions du submesh global
  31564. meshSubclass.releaseSubMeshes();
  31565. index = 0;
  31566. var offset = 0;
  31567. //-- aplique la subdivision en fonction du tableau d'indices
  31568. while (index < indiceArray.length) {
  31569. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  31570. offset += indiceArray[index];
  31571. index++;
  31572. }
  31573. }
  31574. return meshSubclass;
  31575. };
  31576. // Consts
  31577. Mesh._FRONTSIDE = 0;
  31578. Mesh._BACKSIDE = 1;
  31579. Mesh._DOUBLESIDE = 2;
  31580. Mesh._DEFAULTSIDE = 0;
  31581. Mesh._NO_CAP = 0;
  31582. Mesh._CAP_START = 1;
  31583. Mesh._CAP_END = 2;
  31584. Mesh._CAP_ALL = 3;
  31585. return Mesh;
  31586. }(BABYLON.AbstractMesh));
  31587. BABYLON.Mesh = Mesh;
  31588. })(BABYLON || (BABYLON = {}));
  31589. //# sourceMappingURL=babylon.mesh.js.map
  31590. "use strict";
  31591. var BABYLON;
  31592. (function (BABYLON) {
  31593. var BaseSubMesh = /** @class */ (function () {
  31594. function BaseSubMesh() {
  31595. }
  31596. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  31597. get: function () {
  31598. return this._materialEffect;
  31599. },
  31600. enumerable: true,
  31601. configurable: true
  31602. });
  31603. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  31604. if (defines === void 0) { defines = null; }
  31605. if (this._materialEffect === effect) {
  31606. if (!effect) {
  31607. this._materialDefines = null;
  31608. }
  31609. return;
  31610. }
  31611. this._materialDefines = defines;
  31612. this._materialEffect = effect;
  31613. };
  31614. return BaseSubMesh;
  31615. }());
  31616. BABYLON.BaseSubMesh = BaseSubMesh;
  31617. var SubMesh = /** @class */ (function (_super) {
  31618. __extends(SubMesh, _super);
  31619. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  31620. if (createBoundingBox === void 0) { createBoundingBox = true; }
  31621. var _this = _super.call(this) || this;
  31622. _this.materialIndex = materialIndex;
  31623. _this.verticesStart = verticesStart;
  31624. _this.verticesCount = verticesCount;
  31625. _this.indexStart = indexStart;
  31626. _this.indexCount = indexCount;
  31627. _this._renderId = 0;
  31628. _this._mesh = mesh;
  31629. _this._renderingMesh = renderingMesh || mesh;
  31630. mesh.subMeshes.push(_this);
  31631. _this._trianglePlanes = [];
  31632. _this._id = mesh.subMeshes.length - 1;
  31633. if (createBoundingBox) {
  31634. _this.refreshBoundingInfo();
  31635. mesh.computeWorldMatrix(true);
  31636. }
  31637. return _this;
  31638. }
  31639. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  31640. if (createBoundingBox === void 0) { createBoundingBox = true; }
  31641. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  31642. };
  31643. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  31644. get: function () {
  31645. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  31646. },
  31647. enumerable: true,
  31648. configurable: true
  31649. });
  31650. /**
  31651. * Returns the submesh BoudingInfo object.
  31652. */
  31653. SubMesh.prototype.getBoundingInfo = function () {
  31654. if (this.IsGlobal) {
  31655. return this._mesh.getBoundingInfo();
  31656. }
  31657. return this._boundingInfo;
  31658. };
  31659. /**
  31660. * Sets the submesh BoundingInfo.
  31661. * Return the SubMesh.
  31662. */
  31663. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  31664. this._boundingInfo = boundingInfo;
  31665. return this;
  31666. };
  31667. /**
  31668. * Returns the mesh of the current submesh.
  31669. */
  31670. SubMesh.prototype.getMesh = function () {
  31671. return this._mesh;
  31672. };
  31673. /**
  31674. * Returns the rendering mesh of the submesh.
  31675. */
  31676. SubMesh.prototype.getRenderingMesh = function () {
  31677. return this._renderingMesh;
  31678. };
  31679. /**
  31680. * Returns the submesh material.
  31681. */
  31682. SubMesh.prototype.getMaterial = function () {
  31683. var rootMaterial = this._renderingMesh.material;
  31684. if (rootMaterial === null || rootMaterial === undefined) {
  31685. return this._mesh.getScene().defaultMaterial;
  31686. }
  31687. else if (rootMaterial.getSubMaterial) {
  31688. var multiMaterial = rootMaterial;
  31689. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  31690. if (this._currentMaterial !== effectiveMaterial) {
  31691. this._currentMaterial = effectiveMaterial;
  31692. this._materialDefines = null;
  31693. }
  31694. return effectiveMaterial;
  31695. }
  31696. return rootMaterial;
  31697. };
  31698. // Methods
  31699. /**
  31700. * Sets a new updated BoundingInfo object to the submesh.
  31701. * Returns the SubMesh.
  31702. */
  31703. SubMesh.prototype.refreshBoundingInfo = function () {
  31704. this._lastColliderWorldVertices = null;
  31705. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  31706. return this;
  31707. }
  31708. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31709. if (!data) {
  31710. this._boundingInfo = this._mesh.getBoundingInfo();
  31711. return this;
  31712. }
  31713. var indices = this._renderingMesh.getIndices();
  31714. var extend;
  31715. //is this the only submesh?
  31716. if (this.indexStart === 0 && this.indexCount === indices.length) {
  31717. var boundingInfo = this._renderingMesh.getBoundingInfo();
  31718. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  31719. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  31720. }
  31721. else {
  31722. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  31723. }
  31724. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31725. return this;
  31726. };
  31727. SubMesh.prototype._checkCollision = function (collider) {
  31728. var boundingInfo = this.getBoundingInfo();
  31729. return boundingInfo._checkCollision(collider);
  31730. };
  31731. /**
  31732. * Updates the submesh BoundingInfo.
  31733. * Returns the Submesh.
  31734. */
  31735. SubMesh.prototype.updateBoundingInfo = function (world) {
  31736. var boundingInfo = this.getBoundingInfo();
  31737. if (!boundingInfo) {
  31738. this.refreshBoundingInfo();
  31739. boundingInfo = this.getBoundingInfo();
  31740. }
  31741. boundingInfo.update(world);
  31742. return this;
  31743. };
  31744. /**
  31745. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  31746. * Boolean returned.
  31747. */
  31748. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  31749. var boundingInfo = this.getBoundingInfo();
  31750. if (!boundingInfo) {
  31751. return false;
  31752. }
  31753. return boundingInfo.isInFrustum(frustumPlanes);
  31754. };
  31755. /**
  31756. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  31757. * Boolean returned.
  31758. */
  31759. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  31760. var boundingInfo = this.getBoundingInfo();
  31761. if (!boundingInfo) {
  31762. return false;
  31763. }
  31764. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  31765. };
  31766. /**
  31767. * Renders the submesh.
  31768. * Returns it.
  31769. */
  31770. SubMesh.prototype.render = function (enableAlphaMode) {
  31771. this._renderingMesh.render(this, enableAlphaMode);
  31772. return this;
  31773. };
  31774. /**
  31775. * Returns a new Index Buffer.
  31776. * Type returned : WebGLBuffer.
  31777. */
  31778. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  31779. if (!this._linesIndexBuffer) {
  31780. var linesIndices = [];
  31781. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31782. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  31783. }
  31784. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  31785. this.linesIndexCount = linesIndices.length;
  31786. }
  31787. return this._linesIndexBuffer;
  31788. };
  31789. /**
  31790. * True is the passed Ray intersects the submesh bounding box.
  31791. * Boolean returned.
  31792. */
  31793. SubMesh.prototype.canIntersects = function (ray) {
  31794. var boundingInfo = this.getBoundingInfo();
  31795. if (!boundingInfo) {
  31796. return false;
  31797. }
  31798. return ray.intersectsBox(boundingInfo.boundingBox);
  31799. };
  31800. /**
  31801. * Returns an object IntersectionInfo.
  31802. */
  31803. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31804. var intersectInfo = null;
  31805. var material = this.getMaterial();
  31806. if (!material) {
  31807. return null;
  31808. }
  31809. switch (material.fillMode) {
  31810. case BABYLON.Material.PointListDrawMode:
  31811. case BABYLON.Material.LineListDrawMode:
  31812. case BABYLON.Material.LineLoopDrawMode:
  31813. case BABYLON.Material.LineStripDrawMode:
  31814. case BABYLON.Material.TriangleFanDrawMode:
  31815. case BABYLON.Material.TriangleStripDrawMode:
  31816. return null;
  31817. }
  31818. // LineMesh first as it's also a Mesh...
  31819. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31820. var lineMesh = this._mesh;
  31821. // Line test
  31822. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31823. var p0 = positions[indices[index]];
  31824. var p1 = positions[indices[index + 1]];
  31825. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31826. if (length < 0) {
  31827. continue;
  31828. }
  31829. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31830. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31831. if (fastCheck) {
  31832. break;
  31833. }
  31834. }
  31835. }
  31836. }
  31837. else {
  31838. // Triangles test
  31839. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31840. var p0 = positions[indices[index]];
  31841. var p1 = positions[indices[index + 1]];
  31842. var p2 = positions[indices[index + 2]];
  31843. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31844. if (currentIntersectInfo) {
  31845. if (currentIntersectInfo.distance < 0) {
  31846. continue;
  31847. }
  31848. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31849. intersectInfo = currentIntersectInfo;
  31850. intersectInfo.faceId = index / 3;
  31851. if (fastCheck) {
  31852. break;
  31853. }
  31854. }
  31855. }
  31856. }
  31857. }
  31858. return intersectInfo;
  31859. };
  31860. SubMesh.prototype._rebuild = function () {
  31861. if (this._linesIndexBuffer) {
  31862. this._linesIndexBuffer = null;
  31863. }
  31864. };
  31865. // Clone
  31866. /**
  31867. * Creates a new Submesh from the passed Mesh.
  31868. */
  31869. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31870. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31871. if (!this.IsGlobal) {
  31872. var boundingInfo = this.getBoundingInfo();
  31873. if (!boundingInfo) {
  31874. return result;
  31875. }
  31876. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31877. }
  31878. return result;
  31879. };
  31880. // Dispose
  31881. /**
  31882. * Disposes the Submesh.
  31883. * Returns nothing.
  31884. */
  31885. SubMesh.prototype.dispose = function () {
  31886. if (this._linesIndexBuffer) {
  31887. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31888. this._linesIndexBuffer = null;
  31889. }
  31890. // Remove from mesh
  31891. var index = this._mesh.subMeshes.indexOf(this);
  31892. this._mesh.subMeshes.splice(index, 1);
  31893. };
  31894. // Statics
  31895. /**
  31896. * Creates a new Submesh from the passed parameters :
  31897. * - materialIndex (integer) : the index of the main mesh material.
  31898. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31899. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31900. * - mesh (Mesh) : the main mesh to create the submesh from.
  31901. * - renderingMesh (optional Mesh) : rendering mesh.
  31902. */
  31903. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31904. var minVertexIndex = Number.MAX_VALUE;
  31905. var maxVertexIndex = -Number.MAX_VALUE;
  31906. renderingMesh = (renderingMesh || mesh);
  31907. var indices = renderingMesh.getIndices();
  31908. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31909. var vertexIndex = indices[index];
  31910. if (vertexIndex < minVertexIndex)
  31911. minVertexIndex = vertexIndex;
  31912. if (vertexIndex > maxVertexIndex)
  31913. maxVertexIndex = vertexIndex;
  31914. }
  31915. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31916. };
  31917. return SubMesh;
  31918. }(BaseSubMesh));
  31919. BABYLON.SubMesh = SubMesh;
  31920. })(BABYLON || (BABYLON = {}));
  31921. //# sourceMappingURL=babylon.subMesh.js.map
  31922. "use strict";
  31923. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31924. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31925. s = arguments[i];
  31926. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31927. t[p] = s[p];
  31928. }
  31929. return t;
  31930. };
  31931. var BABYLON;
  31932. (function (BABYLON) {
  31933. /**
  31934. * Manages the defines for the Material.
  31935. */
  31936. var MaterialDefines = /** @class */ (function () {
  31937. function MaterialDefines() {
  31938. this._isDirty = true;
  31939. this._areLightsDirty = true;
  31940. this._areAttributesDirty = true;
  31941. this._areTexturesDirty = true;
  31942. this._areFresnelDirty = true;
  31943. this._areMiscDirty = true;
  31944. this._areImageProcessingDirty = true;
  31945. this._normals = false;
  31946. this._uvs = false;
  31947. this._needNormals = false;
  31948. this._needUVs = false;
  31949. }
  31950. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31951. /**
  31952. * Specifies if the material needs to be re-calculated.
  31953. */
  31954. get: function () {
  31955. return this._isDirty;
  31956. },
  31957. enumerable: true,
  31958. configurable: true
  31959. });
  31960. /**
  31961. * Marks the material to indicate that it has been re-calculated.
  31962. */
  31963. MaterialDefines.prototype.markAsProcessed = function () {
  31964. this._isDirty = false;
  31965. this._areAttributesDirty = false;
  31966. this._areTexturesDirty = false;
  31967. this._areFresnelDirty = false;
  31968. this._areLightsDirty = false;
  31969. this._areMiscDirty = false;
  31970. this._areImageProcessingDirty = false;
  31971. };
  31972. /**
  31973. * Marks the material to indicate that it needs to be re-calculated.
  31974. */
  31975. MaterialDefines.prototype.markAsUnprocessed = function () {
  31976. this._isDirty = true;
  31977. };
  31978. /**
  31979. * Marks the material to indicate all of its defines need to be re-calculated.
  31980. */
  31981. MaterialDefines.prototype.markAllAsDirty = function () {
  31982. this._areTexturesDirty = true;
  31983. this._areAttributesDirty = true;
  31984. this._areLightsDirty = true;
  31985. this._areFresnelDirty = true;
  31986. this._areMiscDirty = true;
  31987. this._areImageProcessingDirty = true;
  31988. this._isDirty = true;
  31989. };
  31990. /**
  31991. * Marks the material to indicate that image processing needs to be re-calculated.
  31992. */
  31993. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31994. this._areImageProcessingDirty = true;
  31995. this._isDirty = true;
  31996. };
  31997. /**
  31998. * Marks the material to indicate the lights need to be re-calculated.
  31999. */
  32000. MaterialDefines.prototype.markAsLightDirty = function () {
  32001. this._areLightsDirty = true;
  32002. this._isDirty = true;
  32003. };
  32004. /**
  32005. * Marks the attribute state as changed.
  32006. */
  32007. MaterialDefines.prototype.markAsAttributesDirty = function () {
  32008. this._areAttributesDirty = true;
  32009. this._isDirty = true;
  32010. };
  32011. /**
  32012. * Marks the texture state as changed.
  32013. */
  32014. MaterialDefines.prototype.markAsTexturesDirty = function () {
  32015. this._areTexturesDirty = true;
  32016. this._isDirty = true;
  32017. };
  32018. /**
  32019. * Marks the fresnel state as changed.
  32020. */
  32021. MaterialDefines.prototype.markAsFresnelDirty = function () {
  32022. this._areFresnelDirty = true;
  32023. this._isDirty = true;
  32024. };
  32025. /**
  32026. * Marks the misc state as changed.
  32027. */
  32028. MaterialDefines.prototype.markAsMiscDirty = function () {
  32029. this._areMiscDirty = true;
  32030. this._isDirty = true;
  32031. };
  32032. /**
  32033. * Rebuilds the material defines.
  32034. */
  32035. MaterialDefines.prototype.rebuild = function () {
  32036. if (this._keys) {
  32037. delete this._keys;
  32038. }
  32039. this._keys = [];
  32040. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  32041. var key = _a[_i];
  32042. if (key[0] === "_") {
  32043. continue;
  32044. }
  32045. this._keys.push(key);
  32046. }
  32047. };
  32048. /**
  32049. * Specifies if two material defines are equal.
  32050. * @param other - A material define instance to compare to.
  32051. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  32052. */
  32053. MaterialDefines.prototype.isEqual = function (other) {
  32054. if (this._keys.length !== other._keys.length) {
  32055. return false;
  32056. }
  32057. for (var index = 0; index < this._keys.length; index++) {
  32058. var prop = this._keys[index];
  32059. if (this[prop] !== other[prop]) {
  32060. return false;
  32061. }
  32062. }
  32063. return true;
  32064. };
  32065. /**
  32066. * Clones this instance's defines to another instance.
  32067. * @param other - material defines to clone values to.
  32068. */
  32069. MaterialDefines.prototype.cloneTo = function (other) {
  32070. if (this._keys.length !== other._keys.length) {
  32071. other._keys = this._keys.slice(0);
  32072. }
  32073. for (var index = 0; index < this._keys.length; index++) {
  32074. var prop = this._keys[index];
  32075. other[prop] = this[prop];
  32076. }
  32077. };
  32078. /**
  32079. * Resets the material define values.
  32080. */
  32081. MaterialDefines.prototype.reset = function () {
  32082. for (var index = 0; index < this._keys.length; index++) {
  32083. var prop = this._keys[index];
  32084. var type = typeof this[prop];
  32085. switch (type) {
  32086. case "number":
  32087. this[prop] = 0;
  32088. break;
  32089. case "string":
  32090. this[prop] = "";
  32091. break;
  32092. default:
  32093. this[prop] = false;
  32094. break;
  32095. }
  32096. }
  32097. };
  32098. /**
  32099. * Converts the material define values to a string.
  32100. * @returns - String of material define information.
  32101. */
  32102. MaterialDefines.prototype.toString = function () {
  32103. var result = "";
  32104. for (var index = 0; index < this._keys.length; index++) {
  32105. var prop = this._keys[index];
  32106. var value = this[prop];
  32107. var type = typeof value;
  32108. switch (type) {
  32109. case "number":
  32110. case "string":
  32111. result += "#define " + prop + " " + value + "\n";
  32112. break;
  32113. default:
  32114. if (value) {
  32115. result += "#define " + prop + "\n";
  32116. }
  32117. break;
  32118. }
  32119. }
  32120. return result;
  32121. };
  32122. return MaterialDefines;
  32123. }());
  32124. BABYLON.MaterialDefines = MaterialDefines;
  32125. /**
  32126. * This offers the main features of a material in BJS.
  32127. */
  32128. var Material = /** @class */ (function () {
  32129. /**
  32130. * Creates a material instance.
  32131. * @param name - The name of the material.
  32132. * @param scene - The BJS scene to reference.
  32133. * @param doNotAdd - Specifies if the material should be added to the scene.
  32134. */
  32135. function Material(name, scene, doNotAdd) {
  32136. /**
  32137. * Specifies if the ready state should be checked on each call.
  32138. */
  32139. this.checkReadyOnEveryCall = false;
  32140. /**
  32141. * Specifies if the ready state should be checked once.
  32142. */
  32143. this.checkReadyOnlyOnce = false;
  32144. /**
  32145. * The state of the material.
  32146. */
  32147. this.state = "";
  32148. /**
  32149. * The alpha value of the material.
  32150. */
  32151. this._alpha = 1.0;
  32152. /**
  32153. * Specifies if back face culling is enabled.
  32154. */
  32155. this._backFaceCulling = true;
  32156. /**
  32157. * Specifies if the material should be serialized.
  32158. */
  32159. this.doNotSerialize = false;
  32160. /**
  32161. * Specifies if the effect should be stored on sub meshes.
  32162. */
  32163. this.storeEffectOnSubMeshes = false;
  32164. /**
  32165. * An event triggered when the material is disposed.
  32166. */
  32167. this.onDisposeObservable = new BABYLON.Observable();
  32168. /**
  32169. * An event triggered when the material is bound.
  32170. */
  32171. this.onBindObservable = new BABYLON.Observable();
  32172. /**
  32173. * An event triggered when the material is unbound.
  32174. */
  32175. this.onUnBindObservable = new BABYLON.Observable();
  32176. /**
  32177. * Stores the value of the alpha mode.
  32178. */
  32179. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  32180. /**
  32181. * Stores the state of the need depth pre-pass value.
  32182. */
  32183. this._needDepthPrePass = false;
  32184. /**
  32185. * Specifies if depth writing should be disabled.
  32186. */
  32187. this.disableDepthWrite = false;
  32188. /**
  32189. * Specifies if depth writing should be forced.
  32190. */
  32191. this.forceDepthWrite = false;
  32192. /**
  32193. * Specifies if there should be a separate pass for culling.
  32194. */
  32195. this.separateCullingPass = false;
  32196. /**
  32197. * Stores the state specifing if fog should be enabled.
  32198. */
  32199. this._fogEnabled = true;
  32200. /**
  32201. * Stores the size of points.
  32202. */
  32203. this.pointSize = 1.0;
  32204. /**
  32205. * Stores the z offset value.
  32206. */
  32207. this.zOffset = 0;
  32208. /**
  32209. * Specifies if the material was previously ready.
  32210. */
  32211. this._wasPreviouslyReady = false;
  32212. /**
  32213. * Stores the fill mode state.
  32214. */
  32215. this._fillMode = Material.TriangleFillMode;
  32216. this.name = name;
  32217. this.id = name || BABYLON.Tools.RandomId();
  32218. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  32219. if (this._scene.useRightHandedSystem) {
  32220. this.sideOrientation = Material.ClockWiseSideOrientation;
  32221. }
  32222. else {
  32223. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  32224. }
  32225. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  32226. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  32227. if (!doNotAdd) {
  32228. this._scene.materials.push(this);
  32229. }
  32230. }
  32231. Object.defineProperty(Material, "TriangleFillMode", {
  32232. /**
  32233. * Returns the triangle fill mode.
  32234. */
  32235. get: function () {
  32236. return Material._TriangleFillMode;
  32237. },
  32238. enumerable: true,
  32239. configurable: true
  32240. });
  32241. Object.defineProperty(Material, "WireFrameFillMode", {
  32242. /**
  32243. * Returns the wireframe mode.
  32244. */
  32245. get: function () {
  32246. return Material._WireFrameFillMode;
  32247. },
  32248. enumerable: true,
  32249. configurable: true
  32250. });
  32251. Object.defineProperty(Material, "PointFillMode", {
  32252. /**
  32253. * Returns the point fill mode.
  32254. */
  32255. get: function () {
  32256. return Material._PointFillMode;
  32257. },
  32258. enumerable: true,
  32259. configurable: true
  32260. });
  32261. Object.defineProperty(Material, "PointListDrawMode", {
  32262. /**
  32263. * Returns the point list draw mode.
  32264. */
  32265. get: function () {
  32266. return Material._PointListDrawMode;
  32267. },
  32268. enumerable: true,
  32269. configurable: true
  32270. });
  32271. Object.defineProperty(Material, "LineListDrawMode", {
  32272. /**
  32273. * Returns the line list draw mode.
  32274. */
  32275. get: function () {
  32276. return Material._LineListDrawMode;
  32277. },
  32278. enumerable: true,
  32279. configurable: true
  32280. });
  32281. Object.defineProperty(Material, "LineLoopDrawMode", {
  32282. /**
  32283. * Returns the line loop draw mode.
  32284. */
  32285. get: function () {
  32286. return Material._LineLoopDrawMode;
  32287. },
  32288. enumerable: true,
  32289. configurable: true
  32290. });
  32291. Object.defineProperty(Material, "LineStripDrawMode", {
  32292. /**
  32293. * Returns the line strip draw mode.
  32294. */
  32295. get: function () {
  32296. return Material._LineStripDrawMode;
  32297. },
  32298. enumerable: true,
  32299. configurable: true
  32300. });
  32301. Object.defineProperty(Material, "TriangleStripDrawMode", {
  32302. /**
  32303. * Returns the triangle strip draw mode.
  32304. */
  32305. get: function () {
  32306. return Material._TriangleStripDrawMode;
  32307. },
  32308. enumerable: true,
  32309. configurable: true
  32310. });
  32311. Object.defineProperty(Material, "TriangleFanDrawMode", {
  32312. /**
  32313. * Returns the triangle fan draw mode.
  32314. */
  32315. get: function () {
  32316. return Material._TriangleFanDrawMode;
  32317. },
  32318. enumerable: true,
  32319. configurable: true
  32320. });
  32321. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  32322. /**
  32323. * Returns the clock-wise side orientation.
  32324. */
  32325. get: function () {
  32326. return Material._ClockWiseSideOrientation;
  32327. },
  32328. enumerable: true,
  32329. configurable: true
  32330. });
  32331. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  32332. /**
  32333. * Returns the counter clock-wise side orientation.
  32334. */
  32335. get: function () {
  32336. return Material._CounterClockWiseSideOrientation;
  32337. },
  32338. enumerable: true,
  32339. configurable: true
  32340. });
  32341. Object.defineProperty(Material, "TextureDirtyFlag", {
  32342. /**
  32343. * Returns the dirty texture flag value.
  32344. */
  32345. get: function () {
  32346. return Material._TextureDirtyFlag;
  32347. },
  32348. enumerable: true,
  32349. configurable: true
  32350. });
  32351. Object.defineProperty(Material, "LightDirtyFlag", {
  32352. /**
  32353. * Returns the dirty light flag value.
  32354. */
  32355. get: function () {
  32356. return Material._LightDirtyFlag;
  32357. },
  32358. enumerable: true,
  32359. configurable: true
  32360. });
  32361. Object.defineProperty(Material, "FresnelDirtyFlag", {
  32362. /**
  32363. * Returns the dirty fresnel flag value.
  32364. */
  32365. get: function () {
  32366. return Material._FresnelDirtyFlag;
  32367. },
  32368. enumerable: true,
  32369. configurable: true
  32370. });
  32371. Object.defineProperty(Material, "AttributesDirtyFlag", {
  32372. /**
  32373. * Returns the dirty attributes flag value.
  32374. */
  32375. get: function () {
  32376. return Material._AttributesDirtyFlag;
  32377. },
  32378. enumerable: true,
  32379. configurable: true
  32380. });
  32381. Object.defineProperty(Material, "MiscDirtyFlag", {
  32382. /**
  32383. * Returns the dirty misc flag value.
  32384. */
  32385. get: function () {
  32386. return Material._MiscDirtyFlag;
  32387. },
  32388. enumerable: true,
  32389. configurable: true
  32390. });
  32391. Object.defineProperty(Material.prototype, "alpha", {
  32392. /**
  32393. * Gets the alpha value of the material.
  32394. */
  32395. get: function () {
  32396. return this._alpha;
  32397. },
  32398. /**
  32399. * Sets the alpha value of the material.
  32400. */
  32401. set: function (value) {
  32402. if (this._alpha === value) {
  32403. return;
  32404. }
  32405. this._alpha = value;
  32406. this.markAsDirty(Material.MiscDirtyFlag);
  32407. },
  32408. enumerable: true,
  32409. configurable: true
  32410. });
  32411. Object.defineProperty(Material.prototype, "backFaceCulling", {
  32412. /**
  32413. * Gets the back-face culling state.
  32414. */
  32415. get: function () {
  32416. return this._backFaceCulling;
  32417. },
  32418. /**
  32419. * Sets the back-face culling state.
  32420. */
  32421. set: function (value) {
  32422. if (this._backFaceCulling === value) {
  32423. return;
  32424. }
  32425. this._backFaceCulling = value;
  32426. this.markAsDirty(Material.TextureDirtyFlag);
  32427. },
  32428. enumerable: true,
  32429. configurable: true
  32430. });
  32431. Object.defineProperty(Material.prototype, "onDispose", {
  32432. /**
  32433. * Called during a dispose event.
  32434. */
  32435. set: function (callback) {
  32436. if (this._onDisposeObserver) {
  32437. this.onDisposeObservable.remove(this._onDisposeObserver);
  32438. }
  32439. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  32440. },
  32441. enumerable: true,
  32442. configurable: true
  32443. });
  32444. Object.defineProperty(Material.prototype, "onBind", {
  32445. /**
  32446. * Called during a bind event.
  32447. */
  32448. set: function (callback) {
  32449. if (this._onBindObserver) {
  32450. this.onBindObservable.remove(this._onBindObserver);
  32451. }
  32452. this._onBindObserver = this.onBindObservable.add(callback);
  32453. },
  32454. enumerable: true,
  32455. configurable: true
  32456. });
  32457. Object.defineProperty(Material.prototype, "alphaMode", {
  32458. /**
  32459. * Gets the value of the alpha mode.
  32460. */
  32461. get: function () {
  32462. return this._alphaMode;
  32463. },
  32464. /**
  32465. * Sets the value of the alpha mode.
  32466. *
  32467. * | Value | Type | Description |
  32468. * | --- | --- | --- |
  32469. * | 0 | ALPHA_DISABLE | |
  32470. * | 1 | ALPHA_ADD | |
  32471. * | 2 | ALPHA_COMBINE | |
  32472. * | 3 | ALPHA_SUBTRACT | |
  32473. * | 4 | ALPHA_MULTIPLY | |
  32474. * | 5 | ALPHA_MAXIMIZED | |
  32475. * | 6 | ALPHA_ONEONE | |
  32476. * | 7 | ALPHA_PREMULTIPLIED | |
  32477. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  32478. * | 9 | ALPHA_INTERPOLATE | |
  32479. * | 10 | ALPHA_SCREENMODE | |
  32480. *
  32481. */
  32482. set: function (value) {
  32483. if (this._alphaMode === value) {
  32484. return;
  32485. }
  32486. this._alphaMode = value;
  32487. this.markAsDirty(Material.TextureDirtyFlag);
  32488. },
  32489. enumerable: true,
  32490. configurable: true
  32491. });
  32492. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  32493. /**
  32494. * Gets the depth pre-pass value.
  32495. */
  32496. get: function () {
  32497. return this._needDepthPrePass;
  32498. },
  32499. /**
  32500. * Sets the need depth pre-pass value.
  32501. */
  32502. set: function (value) {
  32503. if (this._needDepthPrePass === value) {
  32504. return;
  32505. }
  32506. this._needDepthPrePass = value;
  32507. if (this._needDepthPrePass) {
  32508. this.checkReadyOnEveryCall = true;
  32509. }
  32510. },
  32511. enumerable: true,
  32512. configurable: true
  32513. });
  32514. Object.defineProperty(Material.prototype, "fogEnabled", {
  32515. /**
  32516. * Gets the value of the fog enabled state.
  32517. */
  32518. get: function () {
  32519. return this._fogEnabled;
  32520. },
  32521. /**
  32522. * Sets the state for enabling fog.
  32523. */
  32524. set: function (value) {
  32525. if (this._fogEnabled === value) {
  32526. return;
  32527. }
  32528. this._fogEnabled = value;
  32529. this.markAsDirty(Material.MiscDirtyFlag);
  32530. },
  32531. enumerable: true,
  32532. configurable: true
  32533. });
  32534. Object.defineProperty(Material.prototype, "wireframe", {
  32535. /**
  32536. * Gets a value specifying if wireframe mode is enabled.
  32537. */
  32538. get: function () {
  32539. switch (this._fillMode) {
  32540. case Material.WireFrameFillMode:
  32541. case Material.LineListDrawMode:
  32542. case Material.LineLoopDrawMode:
  32543. case Material.LineStripDrawMode:
  32544. return true;
  32545. }
  32546. return this._scene.forceWireframe;
  32547. },
  32548. /**
  32549. * Sets the state of wireframe mode.
  32550. */
  32551. set: function (value) {
  32552. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  32553. },
  32554. enumerable: true,
  32555. configurable: true
  32556. });
  32557. Object.defineProperty(Material.prototype, "pointsCloud", {
  32558. /**
  32559. * Gets the value specifying if point clouds are enabled.
  32560. */
  32561. get: function () {
  32562. switch (this._fillMode) {
  32563. case Material.PointFillMode:
  32564. case Material.PointListDrawMode:
  32565. return true;
  32566. }
  32567. return this._scene.forcePointsCloud;
  32568. },
  32569. /**
  32570. * Sets the state of point cloud mode.
  32571. */
  32572. set: function (value) {
  32573. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  32574. },
  32575. enumerable: true,
  32576. configurable: true
  32577. });
  32578. Object.defineProperty(Material.prototype, "fillMode", {
  32579. /**
  32580. * Gets the material fill mode.
  32581. */
  32582. get: function () {
  32583. return this._fillMode;
  32584. },
  32585. /**
  32586. * Sets the material fill mode.
  32587. */
  32588. set: function (value) {
  32589. if (this._fillMode === value) {
  32590. return;
  32591. }
  32592. this._fillMode = value;
  32593. this.markAsDirty(Material.MiscDirtyFlag);
  32594. },
  32595. enumerable: true,
  32596. configurable: true
  32597. });
  32598. /**
  32599. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32600. * subclasses should override adding information pertainent to themselves.
  32601. * @returns - String with material information.
  32602. */
  32603. Material.prototype.toString = function (fullDetails) {
  32604. var ret = "Name: " + this.name;
  32605. if (fullDetails) {
  32606. }
  32607. return ret;
  32608. };
  32609. /**
  32610. * Gets the class name of the material.
  32611. * @returns - String with the class name of the material.
  32612. */
  32613. Material.prototype.getClassName = function () {
  32614. return "Material";
  32615. };
  32616. Object.defineProperty(Material.prototype, "isFrozen", {
  32617. /**
  32618. * Specifies if updates for the material been locked.
  32619. */
  32620. get: function () {
  32621. return this.checkReadyOnlyOnce;
  32622. },
  32623. enumerable: true,
  32624. configurable: true
  32625. });
  32626. /**
  32627. * Locks updates for the material.
  32628. */
  32629. Material.prototype.freeze = function () {
  32630. this.checkReadyOnlyOnce = true;
  32631. };
  32632. /**
  32633. * Unlocks updates for the material.
  32634. */
  32635. Material.prototype.unfreeze = function () {
  32636. this.checkReadyOnlyOnce = false;
  32637. };
  32638. /**
  32639. * Specifies if the material is ready to be used.
  32640. * @param mesh - BJS mesh.
  32641. * @param useInstances - Specifies if instances should be used.
  32642. * @returns - Boolean indicating if the material is ready to be used.
  32643. */
  32644. Material.prototype.isReady = function (mesh, useInstances) {
  32645. return true;
  32646. };
  32647. /**
  32648. * Specifies that the submesh is ready to be used.
  32649. * @param mesh - BJS mesh.
  32650. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  32651. * @param useInstances - Specifies that instances should be used.
  32652. * @returns - boolean indicating that the submesh is ready or not.
  32653. */
  32654. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  32655. return false;
  32656. };
  32657. /**
  32658. * Returns the material effect.
  32659. * @returns - Nullable material effect.
  32660. */
  32661. Material.prototype.getEffect = function () {
  32662. return this._effect;
  32663. };
  32664. /**
  32665. * Returns the BJS scene.
  32666. * @returns - BJS Scene.
  32667. */
  32668. Material.prototype.getScene = function () {
  32669. return this._scene;
  32670. };
  32671. /**
  32672. * Specifies if the material will require alpha blending
  32673. * @returns - Boolean specifying if alpha blending is needed.
  32674. */
  32675. Material.prototype.needAlphaBlending = function () {
  32676. return (this.alpha < 1.0);
  32677. };
  32678. /**
  32679. * Specifies if the mesh will require alpha blending.
  32680. * @param mesh - BJS mesh.
  32681. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  32682. */
  32683. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  32684. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  32685. };
  32686. /**
  32687. * Specifies if this material should be rendered in alpha test mode.
  32688. * @returns - Boolean specifying if an alpha test is needed.
  32689. */
  32690. Material.prototype.needAlphaTesting = function () {
  32691. return false;
  32692. };
  32693. /**
  32694. * Gets the texture used for the alpha test.
  32695. * @returns - Nullable alpha test texture.
  32696. */
  32697. Material.prototype.getAlphaTestTexture = function () {
  32698. return null;
  32699. };
  32700. /**
  32701. * Marks the material to indicate that it needs to be re-calculated.
  32702. */
  32703. Material.prototype.markDirty = function () {
  32704. this._wasPreviouslyReady = false;
  32705. };
  32706. Material.prototype._preBind = function (effect, overrideOrientation) {
  32707. if (overrideOrientation === void 0) { overrideOrientation = null; }
  32708. var engine = this._scene.getEngine();
  32709. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  32710. var reverse = orientation === Material.ClockWiseSideOrientation;
  32711. engine.enableEffect(effect ? effect : this._effect);
  32712. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  32713. return reverse;
  32714. };
  32715. /**
  32716. * Binds the material to the mesh.
  32717. * @param world - World transformation matrix.
  32718. * @param mesh - Mesh to bind the material to.
  32719. */
  32720. Material.prototype.bind = function (world, mesh) {
  32721. };
  32722. /**
  32723. * Binds the submesh to the material.
  32724. * @param world - World transformation matrix.
  32725. * @param mesh - Mesh containing the submesh.
  32726. * @param subMesh - Submesh to bind the material to.
  32727. */
  32728. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32729. };
  32730. /**
  32731. * Binds the world matrix to the material.
  32732. * @param world - World transformation matrix.
  32733. */
  32734. Material.prototype.bindOnlyWorldMatrix = function (world) {
  32735. };
  32736. /**
  32737. * Binds the scene's uniform buffer to the effect.
  32738. * @param effect - Effect to bind to the scene uniform buffer.
  32739. * @param sceneUbo - Scene uniform buffer.
  32740. */
  32741. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  32742. sceneUbo.bindToEffect(effect, "Scene");
  32743. };
  32744. /**
  32745. * Binds the view matrix to the effect.
  32746. * @param effect - Effect to bind the view matrix to.
  32747. */
  32748. Material.prototype.bindView = function (effect) {
  32749. if (!this._useUBO) {
  32750. effect.setMatrix("view", this.getScene().getViewMatrix());
  32751. }
  32752. else {
  32753. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32754. }
  32755. };
  32756. /**
  32757. * Binds the view projection matrix to the effect.
  32758. * @param effect - Effect to bind the view projection matrix to.
  32759. */
  32760. Material.prototype.bindViewProjection = function (effect) {
  32761. if (!this._useUBO) {
  32762. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  32763. }
  32764. else {
  32765. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  32766. }
  32767. };
  32768. /**
  32769. * Specifies if material alpha testing should be turned on for the mesh.
  32770. * @param mesh - BJS mesh.
  32771. */
  32772. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  32773. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  32774. };
  32775. /**
  32776. * Processes to execute after binding the material to a mesh.
  32777. * @param mesh - BJS mesh.
  32778. */
  32779. Material.prototype._afterBind = function (mesh) {
  32780. this._scene._cachedMaterial = this;
  32781. if (mesh) {
  32782. this._scene._cachedVisibility = mesh.visibility;
  32783. }
  32784. else {
  32785. this._scene._cachedVisibility = 1;
  32786. }
  32787. if (mesh) {
  32788. this.onBindObservable.notifyObservers(mesh);
  32789. }
  32790. if (this.disableDepthWrite) {
  32791. var engine = this._scene.getEngine();
  32792. this._cachedDepthWriteState = engine.getDepthWrite();
  32793. engine.setDepthWrite(false);
  32794. }
  32795. };
  32796. /**
  32797. * Unbinds the material from the mesh.
  32798. */
  32799. Material.prototype.unbind = function () {
  32800. this.onUnBindObservable.notifyObservers(this);
  32801. if (this.disableDepthWrite) {
  32802. var engine = this._scene.getEngine();
  32803. engine.setDepthWrite(this._cachedDepthWriteState);
  32804. }
  32805. };
  32806. /**
  32807. * Gets the active textures from the material.
  32808. * @returns - Array of textures.
  32809. */
  32810. Material.prototype.getActiveTextures = function () {
  32811. return [];
  32812. };
  32813. /**
  32814. * Specifies if the material uses a texture.
  32815. * @param texture - Texture to check against the material.
  32816. * @returns - Boolean specifying if the material uses the texture.
  32817. */
  32818. Material.prototype.hasTexture = function (texture) {
  32819. return false;
  32820. };
  32821. /**
  32822. * Makes a duplicate of the material, and gives it a new name.
  32823. * @param name - Name to call the duplicated material.
  32824. * @returns - Nullable cloned material
  32825. */
  32826. Material.prototype.clone = function (name) {
  32827. return null;
  32828. };
  32829. /**
  32830. * Gets the meshes bound to the material.
  32831. * @returns - Array of meshes bound to the material.
  32832. */
  32833. Material.prototype.getBindedMeshes = function () {
  32834. var result = new Array();
  32835. for (var index = 0; index < this._scene.meshes.length; index++) {
  32836. var mesh = this._scene.meshes[index];
  32837. if (mesh.material === this) {
  32838. result.push(mesh);
  32839. }
  32840. }
  32841. return result;
  32842. };
  32843. /**
  32844. * Force shader compilation
  32845. * @param mesh - BJS mesh.
  32846. * @param onCompiled - function to execute once the material is compiled.
  32847. * @param options - options to pass to this function.
  32848. */
  32849. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32850. var _this = this;
  32851. var localOptions = __assign({ clipPlane: false }, options);
  32852. var subMesh = new BABYLON.BaseSubMesh();
  32853. var scene = this.getScene();
  32854. var checkReady = function () {
  32855. if (!_this._scene || !_this._scene.getEngine()) {
  32856. return;
  32857. }
  32858. if (subMesh._materialDefines) {
  32859. subMesh._materialDefines._renderId = -1;
  32860. }
  32861. var clipPlaneState = scene.clipPlane;
  32862. if (localOptions.clipPlane) {
  32863. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32864. }
  32865. if (_this.storeEffectOnSubMeshes) {
  32866. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32867. if (onCompiled) {
  32868. onCompiled(_this);
  32869. }
  32870. }
  32871. else {
  32872. setTimeout(checkReady, 16);
  32873. }
  32874. }
  32875. else {
  32876. if (_this.isReady(mesh)) {
  32877. if (onCompiled) {
  32878. onCompiled(_this);
  32879. }
  32880. }
  32881. else {
  32882. setTimeout(checkReady, 16);
  32883. }
  32884. }
  32885. if (localOptions.clipPlane) {
  32886. scene.clipPlane = clipPlaneState;
  32887. }
  32888. };
  32889. checkReady();
  32890. };
  32891. /**
  32892. * Force shader compilation.
  32893. * @param mesh The mesh that will use this material
  32894. * @param options Additional options for compiling the shaders
  32895. * @returns A promise that resolves when the compilation completes
  32896. */
  32897. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32898. var _this = this;
  32899. return new Promise(function (resolve) {
  32900. _this.forceCompilation(mesh, function () {
  32901. resolve();
  32902. }, options);
  32903. });
  32904. };
  32905. /**
  32906. * Marks a define in the material to indicate that it needs to be re-computed.
  32907. * @param flag - Material define flag.
  32908. */
  32909. Material.prototype.markAsDirty = function (flag) {
  32910. if (flag & Material.TextureDirtyFlag) {
  32911. this._markAllSubMeshesAsTexturesDirty();
  32912. }
  32913. if (flag & Material.LightDirtyFlag) {
  32914. this._markAllSubMeshesAsLightsDirty();
  32915. }
  32916. if (flag & Material.FresnelDirtyFlag) {
  32917. this._markAllSubMeshesAsFresnelDirty();
  32918. }
  32919. if (flag & Material.AttributesDirtyFlag) {
  32920. this._markAllSubMeshesAsAttributesDirty();
  32921. }
  32922. if (flag & Material.MiscDirtyFlag) {
  32923. this._markAllSubMeshesAsMiscDirty();
  32924. }
  32925. this.getScene().resetCachedMaterial();
  32926. };
  32927. /**
  32928. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32929. * @param func - function which checks material defines against the submeshes.
  32930. */
  32931. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32932. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32933. var mesh = _a[_i];
  32934. if (!mesh.subMeshes) {
  32935. continue;
  32936. }
  32937. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32938. var subMesh = _c[_b];
  32939. if (subMesh.getMaterial() !== this) {
  32940. continue;
  32941. }
  32942. if (!subMesh._materialDefines) {
  32943. continue;
  32944. }
  32945. func(subMesh._materialDefines);
  32946. }
  32947. }
  32948. };
  32949. /**
  32950. * Indicates that image processing needs to be re-calculated for all submeshes.
  32951. */
  32952. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32953. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32954. };
  32955. /**
  32956. * Indicates that textures need to be re-calculated for all submeshes.
  32957. */
  32958. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32959. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32960. };
  32961. /**
  32962. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32963. */
  32964. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32965. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32966. };
  32967. /**
  32968. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32969. */
  32970. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32971. this._markAllSubMeshesAsDirty(function (defines) {
  32972. defines.markAsFresnelDirty();
  32973. defines.markAsMiscDirty();
  32974. });
  32975. };
  32976. /**
  32977. * Indicates that lights need to be re-calculated for all submeshes.
  32978. */
  32979. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32980. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32981. };
  32982. /**
  32983. * Indicates that attributes need to be re-calculated for all submeshes.
  32984. */
  32985. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32986. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32987. };
  32988. /**
  32989. * Indicates that misc needs to be re-calculated for all submeshes.
  32990. */
  32991. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32992. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32993. };
  32994. /**
  32995. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32996. */
  32997. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32998. this._markAllSubMeshesAsDirty(function (defines) {
  32999. defines.markAsTexturesDirty();
  33000. defines.markAsMiscDirty();
  33001. });
  33002. };
  33003. /**
  33004. * Disposes the material.
  33005. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  33006. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  33007. */
  33008. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  33009. // Animations
  33010. this.getScene().stopAnimation(this);
  33011. this.getScene().freeProcessedMaterials();
  33012. // Remove from scene
  33013. var index = this._scene.materials.indexOf(this);
  33014. if (index >= 0) {
  33015. this._scene.materials.splice(index, 1);
  33016. }
  33017. // Remove from meshes
  33018. for (index = 0; index < this._scene.meshes.length; index++) {
  33019. var mesh = this._scene.meshes[index];
  33020. if (mesh.material === this) {
  33021. mesh.material = null;
  33022. if (mesh.geometry) {
  33023. var geometry = (mesh.geometry);
  33024. if (this.storeEffectOnSubMeshes) {
  33025. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  33026. var subMesh = _a[_i];
  33027. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  33028. if (forceDisposeEffect && subMesh._materialEffect) {
  33029. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  33030. }
  33031. }
  33032. }
  33033. else {
  33034. geometry._releaseVertexArrayObject(this._effect);
  33035. }
  33036. }
  33037. }
  33038. }
  33039. this._uniformBuffer.dispose();
  33040. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  33041. if (forceDisposeEffect && this._effect) {
  33042. if (!this.storeEffectOnSubMeshes) {
  33043. this._scene.getEngine()._releaseEffect(this._effect);
  33044. }
  33045. this._effect = null;
  33046. }
  33047. // Callback
  33048. this.onDisposeObservable.notifyObservers(this);
  33049. this.onDisposeObservable.clear();
  33050. this.onBindObservable.clear();
  33051. this.onUnBindObservable.clear();
  33052. };
  33053. /**
  33054. * Serializes this material.
  33055. * @returns - serialized material object.
  33056. */
  33057. Material.prototype.serialize = function () {
  33058. return BABYLON.SerializationHelper.Serialize(this);
  33059. };
  33060. /**
  33061. * Creates a MultiMaterial from parse MultiMaterial data.
  33062. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  33063. * @param scene - BJS scene.
  33064. * @returns - MultiMaterial.
  33065. */
  33066. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  33067. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  33068. multiMaterial.id = parsedMultiMaterial.id;
  33069. if (BABYLON.Tags) {
  33070. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  33071. }
  33072. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  33073. var subMatId = parsedMultiMaterial.materials[matIndex];
  33074. if (subMatId) {
  33075. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  33076. }
  33077. else {
  33078. multiMaterial.subMaterials.push(null);
  33079. }
  33080. }
  33081. return multiMaterial;
  33082. };
  33083. /**
  33084. * Creates a material from parsed material data.
  33085. * @param parsedMaterial - Parsed material data.
  33086. * @param scene - BJS scene.
  33087. * @param rootUrl - Root URL containing the material information.
  33088. * @returns - Parsed material.
  33089. */
  33090. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  33091. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  33092. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  33093. }
  33094. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  33095. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  33096. if (!BABYLON.LegacyPBRMaterial) {
  33097. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  33098. return;
  33099. }
  33100. }
  33101. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  33102. return materialType.Parse(parsedMaterial, scene, rootUrl);
  33103. ;
  33104. };
  33105. // Triangle views
  33106. Material._TriangleFillMode = 0;
  33107. Material._WireFrameFillMode = 1;
  33108. Material._PointFillMode = 2;
  33109. // Draw modes
  33110. Material._PointListDrawMode = 3;
  33111. Material._LineListDrawMode = 4;
  33112. Material._LineLoopDrawMode = 5;
  33113. Material._LineStripDrawMode = 6;
  33114. Material._TriangleStripDrawMode = 7;
  33115. Material._TriangleFanDrawMode = 8;
  33116. /**
  33117. * Stores the clock-wise side orientation.
  33118. */
  33119. Material._ClockWiseSideOrientation = 0;
  33120. /**
  33121. * Stores the counter clock-wise side orientation.
  33122. */
  33123. Material._CounterClockWiseSideOrientation = 1;
  33124. /**
  33125. * The dirty texture flag value.
  33126. */
  33127. Material._TextureDirtyFlag = 1;
  33128. /**
  33129. * The dirty light flag value.
  33130. */
  33131. Material._LightDirtyFlag = 2;
  33132. /**
  33133. * The dirty fresnel flag value.
  33134. */
  33135. Material._FresnelDirtyFlag = 4;
  33136. /**
  33137. * The dirty attribute flag value.
  33138. */
  33139. Material._AttributesDirtyFlag = 8;
  33140. /**
  33141. * The dirty misc flag value.
  33142. */
  33143. Material._MiscDirtyFlag = 16;
  33144. __decorate([
  33145. BABYLON.serialize()
  33146. ], Material.prototype, "id", void 0);
  33147. __decorate([
  33148. BABYLON.serialize()
  33149. ], Material.prototype, "name", void 0);
  33150. __decorate([
  33151. BABYLON.serialize()
  33152. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  33153. __decorate([
  33154. BABYLON.serialize()
  33155. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  33156. __decorate([
  33157. BABYLON.serialize()
  33158. ], Material.prototype, "state", void 0);
  33159. __decorate([
  33160. BABYLON.serialize("alpha")
  33161. ], Material.prototype, "_alpha", void 0);
  33162. __decorate([
  33163. BABYLON.serialize("backFaceCulling")
  33164. ], Material.prototype, "_backFaceCulling", void 0);
  33165. __decorate([
  33166. BABYLON.serialize()
  33167. ], Material.prototype, "sideOrientation", void 0);
  33168. __decorate([
  33169. BABYLON.serialize("alphaMode")
  33170. ], Material.prototype, "_alphaMode", void 0);
  33171. __decorate([
  33172. BABYLON.serialize()
  33173. ], Material.prototype, "_needDepthPrePass", void 0);
  33174. __decorate([
  33175. BABYLON.serialize()
  33176. ], Material.prototype, "disableDepthWrite", void 0);
  33177. __decorate([
  33178. BABYLON.serialize()
  33179. ], Material.prototype, "forceDepthWrite", void 0);
  33180. __decorate([
  33181. BABYLON.serialize()
  33182. ], Material.prototype, "separateCullingPass", void 0);
  33183. __decorate([
  33184. BABYLON.serialize("fogEnabled")
  33185. ], Material.prototype, "_fogEnabled", void 0);
  33186. __decorate([
  33187. BABYLON.serialize()
  33188. ], Material.prototype, "pointSize", void 0);
  33189. __decorate([
  33190. BABYLON.serialize()
  33191. ], Material.prototype, "zOffset", void 0);
  33192. __decorate([
  33193. BABYLON.serialize()
  33194. ], Material.prototype, "wireframe", null);
  33195. __decorate([
  33196. BABYLON.serialize()
  33197. ], Material.prototype, "pointsCloud", null);
  33198. __decorate([
  33199. BABYLON.serialize()
  33200. ], Material.prototype, "fillMode", null);
  33201. return Material;
  33202. }());
  33203. BABYLON.Material = Material;
  33204. })(BABYLON || (BABYLON = {}));
  33205. //# sourceMappingURL=babylon.material.js.map
  33206. "use strict";
  33207. var BABYLON;
  33208. (function (BABYLON) {
  33209. var UniformBuffer = /** @class */ (function () {
  33210. /**
  33211. * Uniform buffer objects.
  33212. *
  33213. * Handles blocks of uniform on the GPU.
  33214. *
  33215. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  33216. *
  33217. * For more information, please refer to :
  33218. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  33219. */
  33220. function UniformBuffer(engine, data, dynamic) {
  33221. this._engine = engine;
  33222. this._noUBO = !engine.supportsUniformBuffers;
  33223. this._dynamic = dynamic;
  33224. this._data = data || [];
  33225. this._uniformLocations = {};
  33226. this._uniformSizes = {};
  33227. this._uniformLocationPointer = 0;
  33228. this._needSync = false;
  33229. if (this._noUBO) {
  33230. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  33231. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  33232. this.updateFloat = this._updateFloatForEffect;
  33233. this.updateFloat2 = this._updateFloat2ForEffect;
  33234. this.updateFloat3 = this._updateFloat3ForEffect;
  33235. this.updateFloat4 = this._updateFloat4ForEffect;
  33236. this.updateMatrix = this._updateMatrixForEffect;
  33237. this.updateVector3 = this._updateVector3ForEffect;
  33238. this.updateVector4 = this._updateVector4ForEffect;
  33239. this.updateColor3 = this._updateColor3ForEffect;
  33240. this.updateColor4 = this._updateColor4ForEffect;
  33241. }
  33242. else {
  33243. this._engine._uniformBuffers.push(this);
  33244. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  33245. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  33246. this.updateFloat = this._updateFloatForUniform;
  33247. this.updateFloat2 = this._updateFloat2ForUniform;
  33248. this.updateFloat3 = this._updateFloat3ForUniform;
  33249. this.updateFloat4 = this._updateFloat4ForUniform;
  33250. this.updateMatrix = this._updateMatrixForUniform;
  33251. this.updateVector3 = this._updateVector3ForUniform;
  33252. this.updateVector4 = this._updateVector4ForUniform;
  33253. this.updateColor3 = this._updateColor3ForUniform;
  33254. this.updateColor4 = this._updateColor4ForUniform;
  33255. }
  33256. }
  33257. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  33258. // Properties
  33259. /**
  33260. * Indicates if the buffer is using the WebGL2 UBO implementation,
  33261. * or just falling back on setUniformXXX calls.
  33262. */
  33263. get: function () {
  33264. return !this._noUBO;
  33265. },
  33266. enumerable: true,
  33267. configurable: true
  33268. });
  33269. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  33270. /**
  33271. * Indicates if the WebGL underlying uniform buffer is in sync
  33272. * with the javascript cache data.
  33273. */
  33274. get: function () {
  33275. return !this._needSync;
  33276. },
  33277. enumerable: true,
  33278. configurable: true
  33279. });
  33280. /**
  33281. * Indicates if the WebGL underlying uniform buffer is dynamic.
  33282. * Also, a dynamic UniformBuffer will disable cache verification and always
  33283. * update the underlying WebGL uniform buffer to the GPU.
  33284. */
  33285. UniformBuffer.prototype.isDynamic = function () {
  33286. return this._dynamic !== undefined;
  33287. };
  33288. /**
  33289. * The data cache on JS side.
  33290. */
  33291. UniformBuffer.prototype.getData = function () {
  33292. return this._bufferData;
  33293. };
  33294. /**
  33295. * The underlying WebGL Uniform buffer.
  33296. */
  33297. UniformBuffer.prototype.getBuffer = function () {
  33298. return this._buffer;
  33299. };
  33300. /**
  33301. * std140 layout specifies how to align data within an UBO structure.
  33302. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  33303. * for specs.
  33304. */
  33305. UniformBuffer.prototype._fillAlignment = function (size) {
  33306. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  33307. // and 4x4 matrices
  33308. // TODO : change if other types are used
  33309. var alignment;
  33310. if (size <= 2) {
  33311. alignment = size;
  33312. }
  33313. else {
  33314. alignment = 4;
  33315. }
  33316. if ((this._uniformLocationPointer % alignment) !== 0) {
  33317. var oldPointer = this._uniformLocationPointer;
  33318. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  33319. var diff = this._uniformLocationPointer - oldPointer;
  33320. for (var i = 0; i < diff; i++) {
  33321. this._data.push(0);
  33322. }
  33323. }
  33324. };
  33325. /**
  33326. * Adds an uniform in the buffer.
  33327. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  33328. * for the layout to be correct !
  33329. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33330. * @param {number|number[]} size Data size, or data directly.
  33331. */
  33332. UniformBuffer.prototype.addUniform = function (name, size) {
  33333. if (this._noUBO) {
  33334. return;
  33335. }
  33336. if (this._uniformLocations[name] !== undefined) {
  33337. // Already existing uniform
  33338. return;
  33339. }
  33340. // This function must be called in the order of the shader layout !
  33341. // size can be the size of the uniform, or data directly
  33342. var data;
  33343. if (size instanceof Array) {
  33344. data = size;
  33345. size = data.length;
  33346. }
  33347. else {
  33348. size = size;
  33349. data = [];
  33350. // Fill with zeros
  33351. for (var i = 0; i < size; i++) {
  33352. data.push(0);
  33353. }
  33354. }
  33355. this._fillAlignment(size);
  33356. this._uniformSizes[name] = size;
  33357. this._uniformLocations[name] = this._uniformLocationPointer;
  33358. this._uniformLocationPointer += size;
  33359. for (var i = 0; i < size; i++) {
  33360. this._data.push(data[i]);
  33361. }
  33362. this._needSync = true;
  33363. };
  33364. /**
  33365. * Wrapper for addUniform.
  33366. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33367. * @param {Matrix} mat A 4x4 matrix.
  33368. */
  33369. UniformBuffer.prototype.addMatrix = function (name, mat) {
  33370. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  33371. };
  33372. /**
  33373. * Wrapper for addUniform.
  33374. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33375. * @param {number} x
  33376. * @param {number} y
  33377. */
  33378. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  33379. var temp = [x, y];
  33380. this.addUniform(name, temp);
  33381. };
  33382. /**
  33383. * Wrapper for addUniform.
  33384. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33385. * @param {number} x
  33386. * @param {number} y
  33387. * @param {number} z
  33388. */
  33389. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  33390. var temp = [x, y, z];
  33391. this.addUniform(name, temp);
  33392. };
  33393. /**
  33394. * Wrapper for addUniform.
  33395. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33396. * @param {Color3} color
  33397. */
  33398. UniformBuffer.prototype.addColor3 = function (name, color) {
  33399. var temp = new Array();
  33400. color.toArray(temp);
  33401. this.addUniform(name, temp);
  33402. };
  33403. /**
  33404. * Wrapper for addUniform.
  33405. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33406. * @param {Color3} color
  33407. * @param {number} alpha
  33408. */
  33409. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  33410. var temp = new Array();
  33411. color.toArray(temp);
  33412. temp.push(alpha);
  33413. this.addUniform(name, temp);
  33414. };
  33415. /**
  33416. * Wrapper for addUniform.
  33417. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33418. * @param {Vector3} vector
  33419. */
  33420. UniformBuffer.prototype.addVector3 = function (name, vector) {
  33421. var temp = new Array();
  33422. vector.toArray(temp);
  33423. this.addUniform(name, temp);
  33424. };
  33425. /**
  33426. * Wrapper for addUniform.
  33427. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33428. */
  33429. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  33430. this.addUniform(name, 12);
  33431. };
  33432. /**
  33433. * Wrapper for addUniform.
  33434. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  33435. */
  33436. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  33437. this.addUniform(name, 8);
  33438. };
  33439. /**
  33440. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  33441. */
  33442. UniformBuffer.prototype.create = function () {
  33443. if (this._noUBO) {
  33444. return;
  33445. }
  33446. if (this._buffer) {
  33447. return; // nothing to do
  33448. }
  33449. // See spec, alignment must be filled as a vec4
  33450. this._fillAlignment(4);
  33451. this._bufferData = new Float32Array(this._data);
  33452. this._rebuild();
  33453. this._needSync = true;
  33454. };
  33455. UniformBuffer.prototype._rebuild = function () {
  33456. if (this._noUBO) {
  33457. return;
  33458. }
  33459. if (this._dynamic) {
  33460. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  33461. }
  33462. else {
  33463. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  33464. }
  33465. };
  33466. /**
  33467. * Updates the WebGL Uniform Buffer on the GPU.
  33468. * If the `dynamic` flag is set to true, no cache comparison is done.
  33469. * Otherwise, the buffer will be updated only if the cache differs.
  33470. */
  33471. UniformBuffer.prototype.update = function () {
  33472. if (!this._buffer) {
  33473. this.create();
  33474. return;
  33475. }
  33476. if (!this._dynamic && !this._needSync) {
  33477. return;
  33478. }
  33479. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  33480. this._needSync = false;
  33481. };
  33482. /**
  33483. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  33484. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  33485. * @param {number[]|Float32Array} data Flattened data
  33486. * @param {number} size Size of the data.
  33487. */
  33488. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  33489. var location = this._uniformLocations[uniformName];
  33490. if (location === undefined) {
  33491. if (this._buffer) {
  33492. // Cannot add an uniform if the buffer is already created
  33493. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  33494. return;
  33495. }
  33496. this.addUniform(uniformName, size);
  33497. location = this._uniformLocations[uniformName];
  33498. }
  33499. if (!this._buffer) {
  33500. this.create();
  33501. }
  33502. if (!this._dynamic) {
  33503. // Cache for static uniform buffers
  33504. var changed = false;
  33505. for (var i = 0; i < size; i++) {
  33506. if (this._bufferData[location + i] !== data[i]) {
  33507. changed = true;
  33508. this._bufferData[location + i] = data[i];
  33509. }
  33510. }
  33511. this._needSync = this._needSync || changed;
  33512. }
  33513. else {
  33514. // No cache for dynamic
  33515. for (var i = 0; i < size; i++) {
  33516. this._bufferData[location + i] = data[i];
  33517. }
  33518. }
  33519. };
  33520. // Update methods
  33521. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  33522. // To match std140, matrix must be realigned
  33523. for (var i = 0; i < 3; i++) {
  33524. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  33525. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  33526. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  33527. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  33528. }
  33529. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  33530. };
  33531. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  33532. this._currentEffect.setMatrix3x3(name, matrix);
  33533. };
  33534. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  33535. this._currentEffect.setMatrix2x2(name, matrix);
  33536. };
  33537. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  33538. // To match std140, matrix must be realigned
  33539. for (var i = 0; i < 2; i++) {
  33540. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  33541. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  33542. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  33543. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  33544. }
  33545. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  33546. };
  33547. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  33548. this._currentEffect.setFloat(name, x);
  33549. };
  33550. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  33551. UniformBuffer._tempBuffer[0] = x;
  33552. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  33553. };
  33554. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  33555. if (suffix === void 0) { suffix = ""; }
  33556. this._currentEffect.setFloat2(name + suffix, x, y);
  33557. };
  33558. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  33559. if (suffix === void 0) { suffix = ""; }
  33560. UniformBuffer._tempBuffer[0] = x;
  33561. UniformBuffer._tempBuffer[1] = y;
  33562. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  33563. };
  33564. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  33565. if (suffix === void 0) { suffix = ""; }
  33566. this._currentEffect.setFloat3(name + suffix, x, y, z);
  33567. };
  33568. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  33569. if (suffix === void 0) { suffix = ""; }
  33570. UniformBuffer._tempBuffer[0] = x;
  33571. UniformBuffer._tempBuffer[1] = y;
  33572. UniformBuffer._tempBuffer[2] = z;
  33573. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  33574. };
  33575. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  33576. if (suffix === void 0) { suffix = ""; }
  33577. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  33578. };
  33579. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  33580. if (suffix === void 0) { suffix = ""; }
  33581. UniformBuffer._tempBuffer[0] = x;
  33582. UniformBuffer._tempBuffer[1] = y;
  33583. UniformBuffer._tempBuffer[2] = z;
  33584. UniformBuffer._tempBuffer[3] = w;
  33585. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  33586. };
  33587. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  33588. this._currentEffect.setMatrix(name, mat);
  33589. };
  33590. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  33591. this.updateUniform(name, mat.toArray(), 16);
  33592. };
  33593. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  33594. this._currentEffect.setVector3(name, vector);
  33595. };
  33596. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  33597. vector.toArray(UniformBuffer._tempBuffer);
  33598. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  33599. };
  33600. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  33601. this._currentEffect.setVector4(name, vector);
  33602. };
  33603. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  33604. vector.toArray(UniformBuffer._tempBuffer);
  33605. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  33606. };
  33607. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  33608. if (suffix === void 0) { suffix = ""; }
  33609. this._currentEffect.setColor3(name + suffix, color);
  33610. };
  33611. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  33612. if (suffix === void 0) { suffix = ""; }
  33613. color.toArray(UniformBuffer._tempBuffer);
  33614. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  33615. };
  33616. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  33617. if (suffix === void 0) { suffix = ""; }
  33618. this._currentEffect.setColor4(name + suffix, color, alpha);
  33619. };
  33620. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  33621. if (suffix === void 0) { suffix = ""; }
  33622. color.toArray(UniformBuffer._tempBuffer);
  33623. UniformBuffer._tempBuffer[3] = alpha;
  33624. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  33625. };
  33626. /**
  33627. * Sets a sampler uniform on the effect.
  33628. * @param {string} name Name of the sampler.
  33629. * @param {Texture} texture
  33630. */
  33631. UniformBuffer.prototype.setTexture = function (name, texture) {
  33632. this._currentEffect.setTexture(name, texture);
  33633. };
  33634. /**
  33635. * Directly updates the value of the uniform in the cache AND on the GPU.
  33636. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  33637. * @param {number[]|Float32Array} data Flattened data
  33638. */
  33639. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  33640. this.updateUniform(uniformName, data, data.length);
  33641. this.update();
  33642. };
  33643. /**
  33644. * Binds this uniform buffer to an effect.
  33645. * @param {Effect} effect
  33646. * @param {string} name Name of the uniform block in the shader.
  33647. */
  33648. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  33649. this._currentEffect = effect;
  33650. if (this._noUBO || !this._buffer) {
  33651. return;
  33652. }
  33653. effect.bindUniformBuffer(this._buffer, name);
  33654. };
  33655. /**
  33656. * Disposes the uniform buffer.
  33657. */
  33658. UniformBuffer.prototype.dispose = function () {
  33659. if (this._noUBO) {
  33660. return;
  33661. }
  33662. var index = this._engine._uniformBuffers.indexOf(this);
  33663. if (index !== -1) {
  33664. this._engine._uniformBuffers.splice(index, 1);
  33665. }
  33666. if (!this._buffer) {
  33667. return;
  33668. }
  33669. if (this._engine._releaseBuffer(this._buffer)) {
  33670. this._buffer = null;
  33671. }
  33672. };
  33673. // Pool for avoiding memory leaks
  33674. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  33675. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  33676. return UniformBuffer;
  33677. }());
  33678. BABYLON.UniformBuffer = UniformBuffer;
  33679. })(BABYLON || (BABYLON = {}));
  33680. //# sourceMappingURL=babylon.uniformBuffer.js.map
  33681. "use strict";
  33682. var BABYLON;
  33683. (function (BABYLON) {
  33684. var VertexData = /** @class */ (function () {
  33685. function VertexData() {
  33686. }
  33687. VertexData.prototype.set = function (data, kind) {
  33688. switch (kind) {
  33689. case BABYLON.VertexBuffer.PositionKind:
  33690. this.positions = data;
  33691. break;
  33692. case BABYLON.VertexBuffer.NormalKind:
  33693. this.normals = data;
  33694. break;
  33695. case BABYLON.VertexBuffer.TangentKind:
  33696. this.tangents = data;
  33697. break;
  33698. case BABYLON.VertexBuffer.UVKind:
  33699. this.uvs = data;
  33700. break;
  33701. case BABYLON.VertexBuffer.UV2Kind:
  33702. this.uvs2 = data;
  33703. break;
  33704. case BABYLON.VertexBuffer.UV3Kind:
  33705. this.uvs3 = data;
  33706. break;
  33707. case BABYLON.VertexBuffer.UV4Kind:
  33708. this.uvs4 = data;
  33709. break;
  33710. case BABYLON.VertexBuffer.UV5Kind:
  33711. this.uvs5 = data;
  33712. break;
  33713. case BABYLON.VertexBuffer.UV6Kind:
  33714. this.uvs6 = data;
  33715. break;
  33716. case BABYLON.VertexBuffer.ColorKind:
  33717. this.colors = data;
  33718. break;
  33719. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33720. this.matricesIndices = data;
  33721. break;
  33722. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33723. this.matricesWeights = data;
  33724. break;
  33725. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33726. this.matricesIndicesExtra = data;
  33727. break;
  33728. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33729. this.matricesWeightsExtra = data;
  33730. break;
  33731. }
  33732. };
  33733. /**
  33734. * Associates the vertexData to the passed Mesh.
  33735. * Sets it as updatable or not (default `false`).
  33736. * Returns the VertexData.
  33737. */
  33738. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33739. this._applyTo(mesh, updatable);
  33740. return this;
  33741. };
  33742. /**
  33743. * Associates the vertexData to the passed Geometry.
  33744. * Sets it as updatable or not (default `false`).
  33745. * Returns the VertexData.
  33746. */
  33747. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33748. this._applyTo(geometry, updatable);
  33749. return this;
  33750. };
  33751. /**
  33752. * Updates the associated mesh.
  33753. * Returns the VertexData.
  33754. */
  33755. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33756. this._update(mesh);
  33757. return this;
  33758. };
  33759. /**
  33760. * Updates the associated geometry.
  33761. * Returns the VertexData.
  33762. */
  33763. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33764. this._update(geometry);
  33765. return this;
  33766. };
  33767. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33768. if (updatable === void 0) { updatable = false; }
  33769. if (this.positions) {
  33770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33771. }
  33772. if (this.normals) {
  33773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33774. }
  33775. if (this.tangents) {
  33776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  33777. }
  33778. if (this.uvs) {
  33779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33780. }
  33781. if (this.uvs2) {
  33782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33783. }
  33784. if (this.uvs3) {
  33785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33786. }
  33787. if (this.uvs4) {
  33788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33789. }
  33790. if (this.uvs5) {
  33791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33792. }
  33793. if (this.uvs6) {
  33794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33795. }
  33796. if (this.colors) {
  33797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33798. }
  33799. if (this.matricesIndices) {
  33800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33801. }
  33802. if (this.matricesWeights) {
  33803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33804. }
  33805. if (this.matricesIndicesExtra) {
  33806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33807. }
  33808. if (this.matricesWeightsExtra) {
  33809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33810. }
  33811. if (this.indices) {
  33812. meshOrGeometry.setIndices(this.indices, null, updatable);
  33813. }
  33814. return this;
  33815. };
  33816. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33817. if (this.positions) {
  33818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33819. }
  33820. if (this.normals) {
  33821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33822. }
  33823. if (this.tangents) {
  33824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33825. }
  33826. if (this.uvs) {
  33827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33828. }
  33829. if (this.uvs2) {
  33830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33831. }
  33832. if (this.uvs3) {
  33833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33834. }
  33835. if (this.uvs4) {
  33836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33837. }
  33838. if (this.uvs5) {
  33839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33840. }
  33841. if (this.uvs6) {
  33842. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33843. }
  33844. if (this.colors) {
  33845. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33846. }
  33847. if (this.matricesIndices) {
  33848. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33849. }
  33850. if (this.matricesWeights) {
  33851. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33852. }
  33853. if (this.matricesIndicesExtra) {
  33854. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33855. }
  33856. if (this.matricesWeightsExtra) {
  33857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33858. }
  33859. if (this.indices) {
  33860. meshOrGeometry.setIndices(this.indices, null);
  33861. }
  33862. return this;
  33863. };
  33864. /**
  33865. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33866. * Returns the VertexData.
  33867. */
  33868. VertexData.prototype.transform = function (matrix) {
  33869. var transformed = BABYLON.Vector3.Zero();
  33870. var index;
  33871. if (this.positions) {
  33872. var position = BABYLON.Vector3.Zero();
  33873. for (index = 0; index < this.positions.length; index += 3) {
  33874. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33875. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33876. this.positions[index] = transformed.x;
  33877. this.positions[index + 1] = transformed.y;
  33878. this.positions[index + 2] = transformed.z;
  33879. }
  33880. }
  33881. if (this.normals) {
  33882. var normal = BABYLON.Vector3.Zero();
  33883. for (index = 0; index < this.normals.length; index += 3) {
  33884. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33885. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33886. this.normals[index] = transformed.x;
  33887. this.normals[index + 1] = transformed.y;
  33888. this.normals[index + 2] = transformed.z;
  33889. }
  33890. }
  33891. if (this.tangents) {
  33892. var tangent = BABYLON.Vector4.Zero();
  33893. var tangentTransformed = BABYLON.Vector4.Zero();
  33894. for (index = 0; index < this.tangents.length; index += 4) {
  33895. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33896. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33897. this.tangents[index] = tangentTransformed.x;
  33898. this.tangents[index + 1] = tangentTransformed.y;
  33899. this.tangents[index + 2] = tangentTransformed.z;
  33900. this.tangents[index + 3] = tangentTransformed.w;
  33901. }
  33902. }
  33903. return this;
  33904. };
  33905. /**
  33906. * Merges the passed VertexData into the current one.
  33907. * Returns the modified VertexData.
  33908. */
  33909. VertexData.prototype.merge = function (other) {
  33910. this._validate();
  33911. other._validate();
  33912. if (!this.normals !== !other.normals ||
  33913. !this.tangents !== !other.tangents ||
  33914. !this.uvs !== !other.uvs ||
  33915. !this.uvs2 !== !other.uvs2 ||
  33916. !this.uvs3 !== !other.uvs3 ||
  33917. !this.uvs4 !== !other.uvs4 ||
  33918. !this.uvs5 !== !other.uvs5 ||
  33919. !this.uvs6 !== !other.uvs6 ||
  33920. !this.colors !== !other.colors ||
  33921. !this.matricesIndices !== !other.matricesIndices ||
  33922. !this.matricesWeights !== !other.matricesWeights ||
  33923. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33924. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33925. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33926. }
  33927. if (other.indices) {
  33928. if (!this.indices) {
  33929. this.indices = [];
  33930. }
  33931. var offset = this.positions ? this.positions.length / 3 : 0;
  33932. for (var index = 0; index < other.indices.length; index++) {
  33933. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33934. this.indices.push(other.indices[index] + offset);
  33935. }
  33936. }
  33937. this.positions = this._mergeElement(this.positions, other.positions);
  33938. this.normals = this._mergeElement(this.normals, other.normals);
  33939. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33940. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33941. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33942. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33943. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33944. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33945. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33946. this.colors = this._mergeElement(this.colors, other.colors);
  33947. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33948. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33949. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33950. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33951. return this;
  33952. };
  33953. VertexData.prototype._mergeElement = function (source, other) {
  33954. if (!source) {
  33955. return other;
  33956. }
  33957. if (!other) {
  33958. return source;
  33959. }
  33960. var len = other.length + source.length;
  33961. var isSrcTypedArray = source instanceof Float32Array;
  33962. var isOthTypedArray = other instanceof Float32Array;
  33963. // use non-loop method when the source is Float32Array
  33964. if (isSrcTypedArray) {
  33965. var ret32 = new Float32Array(len);
  33966. ret32.set(source);
  33967. ret32.set(other, source.length);
  33968. return ret32;
  33969. // source is number[], when other is also use concat
  33970. }
  33971. else if (!isOthTypedArray) {
  33972. return source.concat(other);
  33973. // source is a number[], but other is a Float32Array, loop required
  33974. }
  33975. else {
  33976. var ret = source.slice(0); // copy source to a separate array
  33977. for (var i = 0, len = other.length; i < len; i++) {
  33978. ret.push(other[i]);
  33979. }
  33980. return ret;
  33981. }
  33982. };
  33983. VertexData.prototype._validate = function () {
  33984. if (!this.positions) {
  33985. throw new Error("Positions are required");
  33986. }
  33987. var getElementCount = function (kind, values) {
  33988. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33989. if ((values.length % stride) !== 0) {
  33990. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33991. }
  33992. return values.length / stride;
  33993. };
  33994. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33995. var validateElementCount = function (kind, values) {
  33996. var elementCount = getElementCount(kind, values);
  33997. if (elementCount !== positionsElementCount) {
  33998. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33999. }
  34000. };
  34001. if (this.normals)
  34002. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  34003. if (this.tangents)
  34004. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  34005. if (this.uvs)
  34006. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  34007. if (this.uvs2)
  34008. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  34009. if (this.uvs3)
  34010. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  34011. if (this.uvs4)
  34012. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  34013. if (this.uvs5)
  34014. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  34015. if (this.uvs6)
  34016. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  34017. if (this.colors)
  34018. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  34019. if (this.matricesIndices)
  34020. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  34021. if (this.matricesWeights)
  34022. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  34023. if (this.matricesIndicesExtra)
  34024. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  34025. if (this.matricesWeightsExtra)
  34026. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  34027. };
  34028. /**
  34029. * Serializes the VertexData.
  34030. * Returns a serialized object.
  34031. */
  34032. VertexData.prototype.serialize = function () {
  34033. var serializationObject = this.serialize();
  34034. if (this.positions) {
  34035. serializationObject.positions = this.positions;
  34036. }
  34037. if (this.normals) {
  34038. serializationObject.normals = this.normals;
  34039. }
  34040. if (this.tangents) {
  34041. serializationObject.tangents = this.tangents;
  34042. }
  34043. if (this.uvs) {
  34044. serializationObject.uvs = this.uvs;
  34045. }
  34046. if (this.uvs2) {
  34047. serializationObject.uvs2 = this.uvs2;
  34048. }
  34049. if (this.uvs3) {
  34050. serializationObject.uvs3 = this.uvs3;
  34051. }
  34052. if (this.uvs4) {
  34053. serializationObject.uvs4 = this.uvs4;
  34054. }
  34055. if (this.uvs5) {
  34056. serializationObject.uvs5 = this.uvs5;
  34057. }
  34058. if (this.uvs6) {
  34059. serializationObject.uvs6 = this.uvs6;
  34060. }
  34061. if (this.colors) {
  34062. serializationObject.colors = this.colors;
  34063. }
  34064. if (this.matricesIndices) {
  34065. serializationObject.matricesIndices = this.matricesIndices;
  34066. serializationObject.matricesIndices._isExpanded = true;
  34067. }
  34068. if (this.matricesWeights) {
  34069. serializationObject.matricesWeights = this.matricesWeights;
  34070. }
  34071. if (this.matricesIndicesExtra) {
  34072. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  34073. serializationObject.matricesIndicesExtra._isExpanded = true;
  34074. }
  34075. if (this.matricesWeightsExtra) {
  34076. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  34077. }
  34078. serializationObject.indices = this.indices;
  34079. return serializationObject;
  34080. };
  34081. // Statics
  34082. /**
  34083. * Returns the object VertexData associated to the passed mesh.
  34084. */
  34085. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  34086. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  34087. };
  34088. /**
  34089. * Returns the object VertexData associated to the passed geometry.
  34090. */
  34091. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  34092. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  34093. };
  34094. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  34095. var result = new VertexData();
  34096. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34097. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  34098. }
  34099. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34100. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  34101. }
  34102. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34103. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  34104. }
  34105. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34106. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  34107. }
  34108. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34109. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  34110. }
  34111. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34112. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  34113. }
  34114. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34115. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  34116. }
  34117. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34118. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  34119. }
  34120. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34121. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  34122. }
  34123. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34124. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  34125. }
  34126. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34127. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  34128. }
  34129. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34130. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  34131. }
  34132. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  34133. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  34134. }
  34135. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  34136. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  34137. }
  34138. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  34139. return result;
  34140. };
  34141. /**
  34142. * Creates the vertexData of the Ribbon.
  34143. */
  34144. VertexData.CreateRibbon = function (options) {
  34145. var pathArray = options.pathArray;
  34146. var closeArray = options.closeArray || false;
  34147. var closePath = options.closePath || false;
  34148. var invertUV = options.invertUV || false;
  34149. var defaultOffset = Math.floor(pathArray[0].length / 2);
  34150. var offset = options.offset || defaultOffset;
  34151. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  34152. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34153. var customUV = options.uvs;
  34154. var customColors = options.colors;
  34155. var positions = [];
  34156. var indices = [];
  34157. var normals = [];
  34158. var uvs = [];
  34159. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  34160. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  34161. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  34162. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  34163. var minlg; // minimal length among all paths from pathArray
  34164. var lg = []; // array of path lengths : nb of vertex per path
  34165. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  34166. var p; // path iterator
  34167. var i; // point iterator
  34168. var j; // point iterator
  34169. // if single path in pathArray
  34170. if (pathArray.length < 2) {
  34171. var ar1 = [];
  34172. var ar2 = [];
  34173. for (i = 0; i < pathArray[0].length - offset; i++) {
  34174. ar1.push(pathArray[0][i]);
  34175. ar2.push(pathArray[0][i + offset]);
  34176. }
  34177. pathArray = [ar1, ar2];
  34178. }
  34179. // positions and horizontal distances (u)
  34180. var idc = 0;
  34181. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  34182. var path;
  34183. var l;
  34184. minlg = pathArray[0].length;
  34185. var vectlg;
  34186. var dist;
  34187. for (p = 0; p < pathArray.length; p++) {
  34188. uTotalDistance[p] = 0;
  34189. us[p] = [0];
  34190. path = pathArray[p];
  34191. l = path.length;
  34192. minlg = (minlg < l) ? minlg : l;
  34193. j = 0;
  34194. while (j < l) {
  34195. positions.push(path[j].x, path[j].y, path[j].z);
  34196. if (j > 0) {
  34197. vectlg = path[j].subtract(path[j - 1]).length();
  34198. dist = vectlg + uTotalDistance[p];
  34199. us[p].push(dist);
  34200. uTotalDistance[p] = dist;
  34201. }
  34202. j++;
  34203. }
  34204. if (closePath) {
  34205. j--;
  34206. positions.push(path[0].x, path[0].y, path[0].z);
  34207. vectlg = path[j].subtract(path[0]).length();
  34208. dist = vectlg + uTotalDistance[p];
  34209. us[p].push(dist);
  34210. uTotalDistance[p] = dist;
  34211. }
  34212. lg[p] = l + closePathCorr;
  34213. idx[p] = idc;
  34214. idc += (l + closePathCorr);
  34215. }
  34216. // vertical distances (v)
  34217. var path1;
  34218. var path2;
  34219. var vertex1 = null;
  34220. var vertex2 = null;
  34221. for (i = 0; i < minlg + closePathCorr; i++) {
  34222. vTotalDistance[i] = 0;
  34223. vs[i] = [0];
  34224. for (p = 0; p < pathArray.length - 1; p++) {
  34225. path1 = pathArray[p];
  34226. path2 = pathArray[p + 1];
  34227. if (i === minlg) {
  34228. vertex1 = path1[0];
  34229. vertex2 = path2[0];
  34230. }
  34231. else {
  34232. vertex1 = path1[i];
  34233. vertex2 = path2[i];
  34234. }
  34235. vectlg = vertex2.subtract(vertex1).length();
  34236. dist = vectlg + vTotalDistance[i];
  34237. vs[i].push(dist);
  34238. vTotalDistance[i] = dist;
  34239. }
  34240. if (closeArray && vertex2 && vertex1) {
  34241. path1 = pathArray[p];
  34242. path2 = pathArray[0];
  34243. if (i === minlg) {
  34244. vertex2 = path2[0];
  34245. }
  34246. vectlg = vertex2.subtract(vertex1).length();
  34247. dist = vectlg + vTotalDistance[i];
  34248. vTotalDistance[i] = dist;
  34249. }
  34250. }
  34251. // uvs
  34252. var u;
  34253. var v;
  34254. if (customUV) {
  34255. for (p = 0; p < customUV.length; p++) {
  34256. uvs.push(customUV[p].x, customUV[p].y);
  34257. }
  34258. }
  34259. else {
  34260. for (p = 0; p < pathArray.length; p++) {
  34261. for (i = 0; i < minlg + closePathCorr; i++) {
  34262. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  34263. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  34264. if (invertUV) {
  34265. uvs.push(v, u);
  34266. }
  34267. else {
  34268. uvs.push(u, v);
  34269. }
  34270. }
  34271. }
  34272. }
  34273. // indices
  34274. p = 0; // path index
  34275. var pi = 0; // positions array index
  34276. var l1 = lg[p] - 1; // path1 length
  34277. var l2 = lg[p + 1] - 1; // path2 length
  34278. var min = (l1 < l2) ? l1 : l2; // current path stop index
  34279. var shft = idx[1] - idx[0]; // shift
  34280. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  34281. while (pi <= min && p < path1nb) {
  34282. // 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
  34283. indices.push(pi, pi + shft, pi + 1);
  34284. indices.push(pi + shft + 1, pi + 1, pi + shft);
  34285. pi += 1;
  34286. if (pi === min) {
  34287. p++;
  34288. if (p === lg.length - 1) {
  34289. shft = idx[0] - idx[p];
  34290. l1 = lg[p] - 1;
  34291. l2 = lg[0] - 1;
  34292. }
  34293. else {
  34294. shft = idx[p + 1] - idx[p];
  34295. l1 = lg[p] - 1;
  34296. l2 = lg[p + 1] - 1;
  34297. }
  34298. pi = idx[p];
  34299. min = (l1 < l2) ? l1 + pi : l2 + pi;
  34300. }
  34301. }
  34302. // normals
  34303. VertexData.ComputeNormals(positions, indices, normals);
  34304. if (closePath) {
  34305. var indexFirst = 0;
  34306. var indexLast = 0;
  34307. for (p = 0; p < pathArray.length; p++) {
  34308. indexFirst = idx[p] * 3;
  34309. if (p + 1 < pathArray.length) {
  34310. indexLast = (idx[p + 1] - 1) * 3;
  34311. }
  34312. else {
  34313. indexLast = normals.length - 3;
  34314. }
  34315. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  34316. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  34317. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  34318. normals[indexLast] = normals[indexFirst];
  34319. normals[indexLast + 1] = normals[indexFirst + 1];
  34320. normals[indexLast + 2] = normals[indexFirst + 2];
  34321. }
  34322. }
  34323. // sides
  34324. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34325. // Colors
  34326. var colors = null;
  34327. if (customColors) {
  34328. colors = new Float32Array(customColors.length * 4);
  34329. for (var c = 0; c < customColors.length; c++) {
  34330. colors[c * 4] = customColors[c].r;
  34331. colors[c * 4 + 1] = customColors[c].g;
  34332. colors[c * 4 + 2] = customColors[c].b;
  34333. colors[c * 4 + 3] = customColors[c].a;
  34334. }
  34335. }
  34336. // Result
  34337. var vertexData = new VertexData();
  34338. var positions32 = new Float32Array(positions);
  34339. var normals32 = new Float32Array(normals);
  34340. var uvs32 = new Float32Array(uvs);
  34341. vertexData.indices = indices;
  34342. vertexData.positions = positions32;
  34343. vertexData.normals = normals32;
  34344. vertexData.uvs = uvs32;
  34345. if (colors) {
  34346. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  34347. }
  34348. if (closePath) {
  34349. vertexData._idx = idx;
  34350. }
  34351. return vertexData;
  34352. };
  34353. /**
  34354. * Creates the VertexData of the Box.
  34355. */
  34356. VertexData.CreateBox = function (options) {
  34357. var normalsSource = [
  34358. new BABYLON.Vector3(0, 0, 1),
  34359. new BABYLON.Vector3(0, 0, -1),
  34360. new BABYLON.Vector3(1, 0, 0),
  34361. new BABYLON.Vector3(-1, 0, 0),
  34362. new BABYLON.Vector3(0, 1, 0),
  34363. new BABYLON.Vector3(0, -1, 0)
  34364. ];
  34365. var indices = [];
  34366. var positions = [];
  34367. var normals = [];
  34368. var uvs = [];
  34369. var width = options.width || options.size || 1;
  34370. var height = options.height || options.size || 1;
  34371. var depth = options.depth || options.size || 1;
  34372. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34373. var faceUV = options.faceUV || new Array(6);
  34374. var faceColors = options.faceColors;
  34375. var colors = [];
  34376. // default face colors and UV if undefined
  34377. for (var f = 0; f < 6; f++) {
  34378. if (faceUV[f] === undefined) {
  34379. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34380. }
  34381. if (faceColors && faceColors[f] === undefined) {
  34382. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34383. }
  34384. }
  34385. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  34386. // Create each face in turn.
  34387. for (var index = 0; index < normalsSource.length; index++) {
  34388. var normal = normalsSource[index];
  34389. // Get two vectors perpendicular to the face normal and to each other.
  34390. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  34391. var side2 = BABYLON.Vector3.Cross(normal, side1);
  34392. // Six indices (two triangles) per face.
  34393. var verticesLength = positions.length / 3;
  34394. indices.push(verticesLength);
  34395. indices.push(verticesLength + 1);
  34396. indices.push(verticesLength + 2);
  34397. indices.push(verticesLength);
  34398. indices.push(verticesLength + 2);
  34399. indices.push(verticesLength + 3);
  34400. // Four vertices per face.
  34401. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  34402. positions.push(vertex.x, vertex.y, vertex.z);
  34403. normals.push(normal.x, normal.y, normal.z);
  34404. uvs.push(faceUV[index].z, faceUV[index].w);
  34405. if (faceColors) {
  34406. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34407. }
  34408. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  34409. positions.push(vertex.x, vertex.y, vertex.z);
  34410. normals.push(normal.x, normal.y, normal.z);
  34411. uvs.push(faceUV[index].x, faceUV[index].w);
  34412. if (faceColors) {
  34413. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34414. }
  34415. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  34416. positions.push(vertex.x, vertex.y, vertex.z);
  34417. normals.push(normal.x, normal.y, normal.z);
  34418. uvs.push(faceUV[index].x, faceUV[index].y);
  34419. if (faceColors) {
  34420. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34421. }
  34422. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  34423. positions.push(vertex.x, vertex.y, vertex.z);
  34424. normals.push(normal.x, normal.y, normal.z);
  34425. uvs.push(faceUV[index].z, faceUV[index].y);
  34426. if (faceColors) {
  34427. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  34428. }
  34429. }
  34430. // sides
  34431. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34432. // Result
  34433. var vertexData = new VertexData();
  34434. vertexData.indices = indices;
  34435. vertexData.positions = positions;
  34436. vertexData.normals = normals;
  34437. vertexData.uvs = uvs;
  34438. if (faceColors) {
  34439. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34440. vertexData.colors = totalColors;
  34441. }
  34442. return vertexData;
  34443. };
  34444. /**
  34445. * Creates the VertexData of the Sphere.
  34446. */
  34447. VertexData.CreateSphere = function (options) {
  34448. var segments = options.segments || 32;
  34449. var diameterX = options.diameterX || options.diameter || 1;
  34450. var diameterY = options.diameterY || options.diameter || 1;
  34451. var diameterZ = options.diameterZ || options.diameter || 1;
  34452. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34453. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  34454. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34455. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  34456. var totalZRotationSteps = 2 + segments;
  34457. var totalYRotationSteps = 2 * totalZRotationSteps;
  34458. var indices = [];
  34459. var positions = [];
  34460. var normals = [];
  34461. var uvs = [];
  34462. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  34463. var normalizedZ = zRotationStep / totalZRotationSteps;
  34464. var angleZ = normalizedZ * Math.PI * slice;
  34465. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  34466. var normalizedY = yRotationStep / totalYRotationSteps;
  34467. var angleY = normalizedY * Math.PI * 2 * arc;
  34468. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  34469. var rotationY = BABYLON.Matrix.RotationY(angleY);
  34470. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  34471. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  34472. var vertex = complete.multiply(radius);
  34473. var normal = complete.divide(radius).normalize();
  34474. positions.push(vertex.x, vertex.y, vertex.z);
  34475. normals.push(normal.x, normal.y, normal.z);
  34476. uvs.push(normalizedY, normalizedZ);
  34477. }
  34478. if (zRotationStep > 0) {
  34479. var verticesCount = positions.length / 3;
  34480. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  34481. indices.push((firstIndex));
  34482. indices.push((firstIndex + 1));
  34483. indices.push(firstIndex + totalYRotationSteps + 1);
  34484. indices.push((firstIndex + totalYRotationSteps + 1));
  34485. indices.push((firstIndex + 1));
  34486. indices.push((firstIndex + totalYRotationSteps + 2));
  34487. }
  34488. }
  34489. }
  34490. // Sides
  34491. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34492. // Result
  34493. var vertexData = new VertexData();
  34494. vertexData.indices = indices;
  34495. vertexData.positions = positions;
  34496. vertexData.normals = normals;
  34497. vertexData.uvs = uvs;
  34498. return vertexData;
  34499. };
  34500. /**
  34501. * Creates the VertexData of the Cylinder or Cone.
  34502. */
  34503. VertexData.CreateCylinder = function (options) {
  34504. var height = options.height || 2;
  34505. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  34506. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  34507. var tessellation = options.tessellation || 24;
  34508. var subdivisions = options.subdivisions || 1;
  34509. var hasRings = options.hasRings ? true : false;
  34510. var enclose = options.enclose ? true : false;
  34511. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34512. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34513. var faceUV = options.faceUV || new Array(3);
  34514. var faceColors = options.faceColors;
  34515. // default face colors and UV if undefined
  34516. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  34517. var ringNb = (hasRings) ? subdivisions : 1;
  34518. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  34519. var f;
  34520. for (f = 0; f < surfaceNb; f++) {
  34521. if (faceColors && faceColors[f] === undefined) {
  34522. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34523. }
  34524. }
  34525. for (f = 0; f < surfaceNb; f++) {
  34526. if (faceUV && faceUV[f] === undefined) {
  34527. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34528. }
  34529. }
  34530. var indices = new Array();
  34531. var positions = new Array();
  34532. var normals = new Array();
  34533. var uvs = new Array();
  34534. var colors = new Array();
  34535. var angle_step = Math.PI * 2 * arc / tessellation;
  34536. var angle;
  34537. var h;
  34538. var radius;
  34539. var tan = (diameterBottom - diameterTop) / 2 / height;
  34540. var ringVertex = BABYLON.Vector3.Zero();
  34541. var ringNormal = BABYLON.Vector3.Zero();
  34542. var ringFirstVertex = BABYLON.Vector3.Zero();
  34543. var ringFirstNormal = BABYLON.Vector3.Zero();
  34544. var quadNormal = BABYLON.Vector3.Zero();
  34545. var Y = BABYLON.Axis.Y;
  34546. // positions, normals, uvs
  34547. var i;
  34548. var j;
  34549. var r;
  34550. var ringIdx = 1;
  34551. var s = 1; // surface index
  34552. var cs = 0;
  34553. var v = 0;
  34554. for (i = 0; i <= subdivisions; i++) {
  34555. h = i / subdivisions;
  34556. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  34557. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  34558. for (r = 0; r < ringIdx; r++) {
  34559. if (hasRings) {
  34560. s += r;
  34561. }
  34562. if (enclose) {
  34563. s += 2 * r;
  34564. }
  34565. for (j = 0; j <= tessellation; j++) {
  34566. angle = j * angle_step;
  34567. // position
  34568. ringVertex.x = Math.cos(-angle) * radius;
  34569. ringVertex.y = -height / 2 + h * height;
  34570. ringVertex.z = Math.sin(-angle) * radius;
  34571. // normal
  34572. if (diameterTop === 0 && i === subdivisions) {
  34573. // if no top cap, reuse former normals
  34574. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  34575. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  34576. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  34577. }
  34578. else {
  34579. ringNormal.x = ringVertex.x;
  34580. ringNormal.z = ringVertex.z;
  34581. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  34582. ringNormal.normalize();
  34583. }
  34584. // keep first ring vertex values for enclose
  34585. if (j === 0) {
  34586. ringFirstVertex.copyFrom(ringVertex);
  34587. ringFirstNormal.copyFrom(ringNormal);
  34588. }
  34589. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34590. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  34591. if (hasRings) {
  34592. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  34593. }
  34594. else {
  34595. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  34596. }
  34597. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  34598. if (faceColors) {
  34599. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  34600. }
  34601. }
  34602. // if enclose, add four vertices and their dedicated normals
  34603. if (arc !== 1 && enclose) {
  34604. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34605. positions.push(0, ringVertex.y, 0);
  34606. positions.push(0, ringVertex.y, 0);
  34607. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  34608. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  34609. quadNormal.normalize();
  34610. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34611. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  34612. quadNormal.normalize();
  34613. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34614. if (hasRings) {
  34615. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  34616. }
  34617. else {
  34618. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  34619. }
  34620. uvs.push(faceUV[s + 1].x, v);
  34621. uvs.push(faceUV[s + 1].z, v);
  34622. if (hasRings) {
  34623. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  34624. }
  34625. else {
  34626. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  34627. }
  34628. uvs.push(faceUV[s + 2].x, v);
  34629. uvs.push(faceUV[s + 2].z, v);
  34630. if (faceColors) {
  34631. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34632. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34633. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34634. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34635. }
  34636. }
  34637. if (cs !== s) {
  34638. cs = s;
  34639. }
  34640. }
  34641. }
  34642. // indices
  34643. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  34644. var s;
  34645. i = 0;
  34646. for (s = 0; s < subdivisions; s++) {
  34647. var i0 = 0;
  34648. var i1 = 0;
  34649. var i2 = 0;
  34650. var i3 = 0;
  34651. for (j = 0; j < tessellation; j++) {
  34652. i0 = i * (e + 1) + j;
  34653. i1 = (i + 1) * (e + 1) + j;
  34654. i2 = i * (e + 1) + (j + 1);
  34655. i3 = (i + 1) * (e + 1) + (j + 1);
  34656. indices.push(i0, i1, i2);
  34657. indices.push(i3, i2, i1);
  34658. }
  34659. if (arc !== 1 && enclose) {
  34660. indices.push(i0 + 2, i1 + 2, i2 + 2);
  34661. indices.push(i3 + 2, i2 + 2, i1 + 2);
  34662. indices.push(i0 + 4, i1 + 4, i2 + 4);
  34663. indices.push(i3 + 4, i2 + 4, i1 + 4);
  34664. }
  34665. i = (hasRings) ? (i + 2) : (i + 1);
  34666. }
  34667. // Caps
  34668. var createCylinderCap = function (isTop) {
  34669. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  34670. if (radius === 0) {
  34671. return;
  34672. }
  34673. // Cap positions, normals & uvs
  34674. var angle;
  34675. var circleVector;
  34676. var i;
  34677. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  34678. var c = null;
  34679. if (faceColors) {
  34680. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  34681. }
  34682. // cap center
  34683. var vbase = positions.length / 3;
  34684. var offset = isTop ? height / 2 : -height / 2;
  34685. var center = new BABYLON.Vector3(0, offset, 0);
  34686. positions.push(center.x, center.y, center.z);
  34687. normals.push(0, isTop ? 1 : -1, 0);
  34688. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  34689. if (c) {
  34690. colors.push(c.r, c.g, c.b, c.a);
  34691. }
  34692. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  34693. for (i = 0; i <= tessellation; i++) {
  34694. angle = Math.PI * 2 * i * arc / tessellation;
  34695. var cos = Math.cos(-angle);
  34696. var sin = Math.sin(-angle);
  34697. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  34698. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  34699. positions.push(circleVector.x, circleVector.y, circleVector.z);
  34700. normals.push(0, isTop ? 1 : -1, 0);
  34701. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  34702. if (c) {
  34703. colors.push(c.r, c.g, c.b, c.a);
  34704. }
  34705. }
  34706. // Cap indices
  34707. for (i = 0; i < tessellation; i++) {
  34708. if (!isTop) {
  34709. indices.push(vbase);
  34710. indices.push(vbase + (i + 1));
  34711. indices.push(vbase + (i + 2));
  34712. }
  34713. else {
  34714. indices.push(vbase);
  34715. indices.push(vbase + (i + 2));
  34716. indices.push(vbase + (i + 1));
  34717. }
  34718. }
  34719. };
  34720. // add caps to geometry
  34721. createCylinderCap(false);
  34722. createCylinderCap(true);
  34723. // Sides
  34724. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34725. var vertexData = new VertexData();
  34726. vertexData.indices = indices;
  34727. vertexData.positions = positions;
  34728. vertexData.normals = normals;
  34729. vertexData.uvs = uvs;
  34730. if (faceColors) {
  34731. vertexData.colors = colors;
  34732. }
  34733. return vertexData;
  34734. };
  34735. /**
  34736. * Creates the VertexData of the Torus.
  34737. */
  34738. VertexData.CreateTorus = function (options) {
  34739. var indices = [];
  34740. var positions = [];
  34741. var normals = [];
  34742. var uvs = [];
  34743. var diameter = options.diameter || 1;
  34744. var thickness = options.thickness || 0.5;
  34745. var tessellation = options.tessellation || 16;
  34746. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34747. var stride = tessellation + 1;
  34748. for (var i = 0; i <= tessellation; i++) {
  34749. var u = i / tessellation;
  34750. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34751. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34752. for (var j = 0; j <= tessellation; j++) {
  34753. var v = 1 - j / tessellation;
  34754. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34755. var dx = Math.cos(innerAngle);
  34756. var dy = Math.sin(innerAngle);
  34757. // Create a vertex.
  34758. var normal = new BABYLON.Vector3(dx, dy, 0);
  34759. var position = normal.scale(thickness / 2);
  34760. var textureCoordinate = new BABYLON.Vector2(u, v);
  34761. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34762. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34763. positions.push(position.x, position.y, position.z);
  34764. normals.push(normal.x, normal.y, normal.z);
  34765. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34766. // And create indices for two triangles.
  34767. var nextI = (i + 1) % stride;
  34768. var nextJ = (j + 1) % stride;
  34769. indices.push(i * stride + j);
  34770. indices.push(i * stride + nextJ);
  34771. indices.push(nextI * stride + j);
  34772. indices.push(i * stride + nextJ);
  34773. indices.push(nextI * stride + nextJ);
  34774. indices.push(nextI * stride + j);
  34775. }
  34776. }
  34777. // Sides
  34778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34779. // Result
  34780. var vertexData = new VertexData();
  34781. vertexData.indices = indices;
  34782. vertexData.positions = positions;
  34783. vertexData.normals = normals;
  34784. vertexData.uvs = uvs;
  34785. return vertexData;
  34786. };
  34787. /**
  34788. * Creates the VertexData of the LineSystem.
  34789. */
  34790. VertexData.CreateLineSystem = function (options) {
  34791. var indices = [];
  34792. var positions = [];
  34793. var lines = options.lines;
  34794. var colors = options.colors;
  34795. var vertexColors = [];
  34796. var idx = 0;
  34797. for (var l = 0; l < lines.length; l++) {
  34798. var points = lines[l];
  34799. for (var index = 0; index < points.length; index++) {
  34800. positions.push(points[index].x, points[index].y, points[index].z);
  34801. if (colors) {
  34802. var color = colors[l];
  34803. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34804. }
  34805. if (index > 0) {
  34806. indices.push(idx - 1);
  34807. indices.push(idx);
  34808. }
  34809. idx++;
  34810. }
  34811. }
  34812. var vertexData = new VertexData();
  34813. vertexData.indices = indices;
  34814. vertexData.positions = positions;
  34815. if (colors) {
  34816. vertexData.colors = vertexColors;
  34817. }
  34818. return vertexData;
  34819. };
  34820. /**
  34821. * Create the VertexData of the DashedLines.
  34822. */
  34823. VertexData.CreateDashedLines = function (options) {
  34824. var dashSize = options.dashSize || 3;
  34825. var gapSize = options.gapSize || 1;
  34826. var dashNb = options.dashNb || 200;
  34827. var points = options.points;
  34828. var positions = new Array();
  34829. var indices = new Array();
  34830. var curvect = BABYLON.Vector3.Zero();
  34831. var lg = 0;
  34832. var nb = 0;
  34833. var shft = 0;
  34834. var dashshft = 0;
  34835. var curshft = 0;
  34836. var idx = 0;
  34837. var i = 0;
  34838. for (i = 0; i < points.length - 1; i++) {
  34839. points[i + 1].subtractToRef(points[i], curvect);
  34840. lg += curvect.length();
  34841. }
  34842. shft = lg / dashNb;
  34843. dashshft = dashSize * shft / (dashSize + gapSize);
  34844. for (i = 0; i < points.length - 1; i++) {
  34845. points[i + 1].subtractToRef(points[i], curvect);
  34846. nb = Math.floor(curvect.length() / shft);
  34847. curvect.normalize();
  34848. for (var j = 0; j < nb; j++) {
  34849. curshft = shft * j;
  34850. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34851. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34852. indices.push(idx, idx + 1);
  34853. idx += 2;
  34854. }
  34855. }
  34856. // Result
  34857. var vertexData = new VertexData();
  34858. vertexData.positions = positions;
  34859. vertexData.indices = indices;
  34860. return vertexData;
  34861. };
  34862. /**
  34863. * Creates the VertexData of the Ground.
  34864. */
  34865. VertexData.CreateGround = function (options) {
  34866. var indices = [];
  34867. var positions = [];
  34868. var normals = [];
  34869. var uvs = [];
  34870. var row, col;
  34871. var width = options.width || 1;
  34872. var height = options.height || 1;
  34873. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34874. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34875. for (row = 0; row <= subdivisionsY; row++) {
  34876. for (col = 0; col <= subdivisionsX; col++) {
  34877. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34878. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34879. positions.push(position.x, position.y, position.z);
  34880. normals.push(normal.x, normal.y, normal.z);
  34881. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34882. }
  34883. }
  34884. for (row = 0; row < subdivisionsY; row++) {
  34885. for (col = 0; col < subdivisionsX; col++) {
  34886. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34887. indices.push(col + 1 + row * (subdivisionsX + 1));
  34888. indices.push(col + row * (subdivisionsX + 1));
  34889. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34890. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34891. indices.push(col + row * (subdivisionsX + 1));
  34892. }
  34893. }
  34894. // Result
  34895. var vertexData = new VertexData();
  34896. vertexData.indices = indices;
  34897. vertexData.positions = positions;
  34898. vertexData.normals = normals;
  34899. vertexData.uvs = uvs;
  34900. return vertexData;
  34901. };
  34902. /**
  34903. * Creates the VertexData of the TiledGround.
  34904. */
  34905. VertexData.CreateTiledGround = function (options) {
  34906. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34907. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34908. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34909. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34910. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34911. var precision = options.precision || { w: 1, h: 1 };
  34912. var indices = new Array();
  34913. var positions = new Array();
  34914. var normals = new Array();
  34915. var uvs = new Array();
  34916. var row, col, tileRow, tileCol;
  34917. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34918. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34919. precision.w = (precision.w < 1) ? 1 : precision.w;
  34920. precision.h = (precision.h < 1) ? 1 : precision.h;
  34921. var tileSize = {
  34922. 'w': (xmax - xmin) / subdivisions.w,
  34923. 'h': (zmax - zmin) / subdivisions.h
  34924. };
  34925. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34926. // Indices
  34927. var base = positions.length / 3;
  34928. var rowLength = precision.w + 1;
  34929. for (row = 0; row < precision.h; row++) {
  34930. for (col = 0; col < precision.w; col++) {
  34931. var square = [
  34932. base + col + row * rowLength,
  34933. base + (col + 1) + row * rowLength,
  34934. base + (col + 1) + (row + 1) * rowLength,
  34935. base + col + (row + 1) * rowLength
  34936. ];
  34937. indices.push(square[1]);
  34938. indices.push(square[2]);
  34939. indices.push(square[3]);
  34940. indices.push(square[0]);
  34941. indices.push(square[1]);
  34942. indices.push(square[3]);
  34943. }
  34944. }
  34945. // Position, normals and uvs
  34946. var position = BABYLON.Vector3.Zero();
  34947. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34948. for (row = 0; row <= precision.h; row++) {
  34949. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34950. for (col = 0; col <= precision.w; col++) {
  34951. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34952. position.y = 0;
  34953. positions.push(position.x, position.y, position.z);
  34954. normals.push(normal.x, normal.y, normal.z);
  34955. uvs.push(col / precision.w, row / precision.h);
  34956. }
  34957. }
  34958. }
  34959. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34960. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34961. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34962. }
  34963. }
  34964. // Result
  34965. var vertexData = new VertexData();
  34966. vertexData.indices = indices;
  34967. vertexData.positions = positions;
  34968. vertexData.normals = normals;
  34969. vertexData.uvs = uvs;
  34970. return vertexData;
  34971. };
  34972. /**
  34973. * Creates the VertexData of the Ground designed from a heightmap.
  34974. */
  34975. VertexData.CreateGroundFromHeightMap = function (options) {
  34976. var indices = [];
  34977. var positions = [];
  34978. var normals = [];
  34979. var uvs = [];
  34980. var row, col;
  34981. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34982. // Vertices
  34983. for (row = 0; row <= options.subdivisions; row++) {
  34984. for (col = 0; col <= options.subdivisions; col++) {
  34985. 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));
  34986. // Compute height
  34987. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34988. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34989. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34990. var r = options.buffer[pos] / 255.0;
  34991. var g = options.buffer[pos + 1] / 255.0;
  34992. var b = options.buffer[pos + 2] / 255.0;
  34993. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34994. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34995. // Add vertex
  34996. positions.push(position.x, position.y, position.z);
  34997. normals.push(0, 0, 0);
  34998. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34999. }
  35000. }
  35001. // Indices
  35002. for (row = 0; row < options.subdivisions; row++) {
  35003. for (col = 0; col < options.subdivisions; col++) {
  35004. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  35005. indices.push(col + 1 + row * (options.subdivisions + 1));
  35006. indices.push(col + row * (options.subdivisions + 1));
  35007. indices.push(col + (row + 1) * (options.subdivisions + 1));
  35008. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  35009. indices.push(col + row * (options.subdivisions + 1));
  35010. }
  35011. }
  35012. // Normals
  35013. VertexData.ComputeNormals(positions, indices, normals);
  35014. // Result
  35015. var vertexData = new VertexData();
  35016. vertexData.indices = indices;
  35017. vertexData.positions = positions;
  35018. vertexData.normals = normals;
  35019. vertexData.uvs = uvs;
  35020. return vertexData;
  35021. };
  35022. /**
  35023. * Creates the VertexData of the Plane.
  35024. */
  35025. VertexData.CreatePlane = function (options) {
  35026. var indices = [];
  35027. var positions = [];
  35028. var normals = [];
  35029. var uvs = [];
  35030. var width = options.width || options.size || 1;
  35031. var height = options.height || options.size || 1;
  35032. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35033. // Vertices
  35034. var halfWidth = width / 2.0;
  35035. var halfHeight = height / 2.0;
  35036. positions.push(-halfWidth, -halfHeight, 0);
  35037. normals.push(0, 0, -1.0);
  35038. uvs.push(0.0, 0.0);
  35039. positions.push(halfWidth, -halfHeight, 0);
  35040. normals.push(0, 0, -1.0);
  35041. uvs.push(1.0, 0.0);
  35042. positions.push(halfWidth, halfHeight, 0);
  35043. normals.push(0, 0, -1.0);
  35044. uvs.push(1.0, 1.0);
  35045. positions.push(-halfWidth, halfHeight, 0);
  35046. normals.push(0, 0, -1.0);
  35047. uvs.push(0.0, 1.0);
  35048. // Indices
  35049. indices.push(0);
  35050. indices.push(1);
  35051. indices.push(2);
  35052. indices.push(0);
  35053. indices.push(2);
  35054. indices.push(3);
  35055. // Sides
  35056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35057. // Result
  35058. var vertexData = new VertexData();
  35059. vertexData.indices = indices;
  35060. vertexData.positions = positions;
  35061. vertexData.normals = normals;
  35062. vertexData.uvs = uvs;
  35063. return vertexData;
  35064. };
  35065. /**
  35066. * Creates the VertexData of the Disc or regular Polygon.
  35067. */
  35068. VertexData.CreateDisc = function (options) {
  35069. var positions = new Array();
  35070. var indices = new Array();
  35071. var normals = new Array();
  35072. var uvs = new Array();
  35073. var radius = options.radius || 0.5;
  35074. var tessellation = options.tessellation || 64;
  35075. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  35076. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35077. // positions and uvs
  35078. positions.push(0, 0, 0); // disc center first
  35079. uvs.push(0.5, 0.5);
  35080. var theta = Math.PI * 2 * arc;
  35081. var step = theta / tessellation;
  35082. for (var a = 0; a < theta; a += step) {
  35083. var x = Math.cos(a);
  35084. var y = Math.sin(a);
  35085. var u = (x + 1) / 2;
  35086. var v = (1 - y) / 2;
  35087. positions.push(radius * x, radius * y, 0);
  35088. uvs.push(u, v);
  35089. }
  35090. if (arc === 1) {
  35091. positions.push(positions[3], positions[4], positions[5]); // close the circle
  35092. uvs.push(uvs[2], uvs[3]);
  35093. }
  35094. //indices
  35095. var vertexNb = positions.length / 3;
  35096. for (var i = 1; i < vertexNb - 1; i++) {
  35097. indices.push(i + 1, 0, i);
  35098. }
  35099. // result
  35100. VertexData.ComputeNormals(positions, indices, normals);
  35101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35102. var vertexData = new VertexData();
  35103. vertexData.indices = indices;
  35104. vertexData.positions = positions;
  35105. vertexData.normals = normals;
  35106. vertexData.uvs = uvs;
  35107. return vertexData;
  35108. };
  35109. /**
  35110. * Re-creates the VertexData of the Polygon for sideOrientation.
  35111. */
  35112. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  35113. var faceUV = fUV || new Array(3);
  35114. var faceColors = fColors;
  35115. var colors = [];
  35116. // default face colors and UV if undefined
  35117. for (var f = 0; f < 3; f++) {
  35118. if (faceUV[f] === undefined) {
  35119. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35120. }
  35121. if (faceColors && faceColors[f] === undefined) {
  35122. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35123. }
  35124. }
  35125. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35126. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35127. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35128. var indices = polygon.getIndices();
  35129. // set face colours and textures
  35130. var idx = 0;
  35131. var face = 0;
  35132. for (var index = 0; index < normals.length; index += 3) {
  35133. //Edge Face no. 1
  35134. if (Math.abs(normals[index + 1]) < 0.001) {
  35135. face = 1;
  35136. }
  35137. //Top Face no. 0
  35138. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  35139. face = 0;
  35140. }
  35141. //Bottom Face no. 2
  35142. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  35143. face = 2;
  35144. }
  35145. idx = index / 3;
  35146. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  35147. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  35148. if (faceColors) {
  35149. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  35150. }
  35151. }
  35152. // sides
  35153. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  35154. // Result
  35155. var vertexData = new VertexData();
  35156. vertexData.indices = indices;
  35157. vertexData.positions = positions;
  35158. vertexData.normals = normals;
  35159. vertexData.uvs = uvs;
  35160. if (faceColors) {
  35161. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  35162. vertexData.colors = totalColors;
  35163. }
  35164. return vertexData;
  35165. };
  35166. /**
  35167. * Creates the VertexData of the IcoSphere.
  35168. */
  35169. VertexData.CreateIcoSphere = function (options) {
  35170. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35171. var radius = options.radius || 1;
  35172. var flat = (options.flat === undefined) ? true : options.flat;
  35173. var subdivisions = options.subdivisions || 4;
  35174. var radiusX = options.radiusX || radius;
  35175. var radiusY = options.radiusY || radius;
  35176. var radiusZ = options.radiusZ || radius;
  35177. var t = (1 + Math.sqrt(5)) / 2;
  35178. // 12 vertex x,y,z
  35179. var ico_vertices = [
  35180. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  35181. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  35182. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  35183. ];
  35184. // index of 3 vertex makes a face of icopshere
  35185. var ico_indices = [
  35186. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  35187. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  35188. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  35189. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  35190. ];
  35191. // vertex for uv have aliased position, not for UV
  35192. var vertices_unalias_id = [
  35193. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  35194. // vertex alias
  35195. 0,
  35196. 2,
  35197. 3,
  35198. 3,
  35199. 3,
  35200. 4,
  35201. 7,
  35202. 8,
  35203. 9,
  35204. 9,
  35205. 10,
  35206. 11 // 23: B + 12
  35207. ];
  35208. // uv as integer step (not pixels !)
  35209. var ico_vertexuv = [
  35210. 5, 1, 3, 1, 6, 4, 0, 0,
  35211. 5, 3, 4, 2, 2, 2, 4, 0,
  35212. 2, 0, 1, 1, 6, 0, 6, 2,
  35213. // vertex alias (for same vertex on different faces)
  35214. 0, 4,
  35215. 3, 3,
  35216. 4, 4,
  35217. 3, 1,
  35218. 4, 2,
  35219. 4, 4,
  35220. 0, 2,
  35221. 1, 1,
  35222. 2, 2,
  35223. 3, 3,
  35224. 1, 3,
  35225. 2, 4 // 23: B + 12
  35226. ];
  35227. // Vertices[0, 1, ...9, A, B] : position on UV plane
  35228. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  35229. // First island of uv mapping
  35230. // v = 4h 3+ 2
  35231. // v = 3h 9+ 4
  35232. // v = 2h 9+ 5 B
  35233. // v = 1h 9 1 0
  35234. // v = 0h 3 8 7 A
  35235. // u = 0 1 2 3 4 5 6 *a
  35236. // Second island of uv mapping
  35237. // v = 4h 0+ B+ 4+
  35238. // v = 3h A+ 2+
  35239. // v = 2h 7+ 6 3+
  35240. // v = 1h 8+ 3+
  35241. // v = 0h
  35242. // u = 0 1 2 3 4 5 6 *a
  35243. // Face layout on texture UV mapping
  35244. // ============
  35245. // \ 4 /\ 16 / ======
  35246. // \ / \ / /\ 11 /
  35247. // \/ 7 \/ / \ /
  35248. // ======= / 10 \/
  35249. // /\ 17 /\ =======
  35250. // / \ / \ \ 15 /\
  35251. // / 8 \/ 12 \ \ / \
  35252. // ============ \/ 6 \
  35253. // \ 18 /\ ============
  35254. // \ / \ \ 5 /\ 0 /
  35255. // \/ 13 \ \ / \ /
  35256. // ======= \/ 1 \/
  35257. // =============
  35258. // /\ 19 /\ 2 /\
  35259. // / \ / \ / \
  35260. // / 14 \/ 9 \/ 3 \
  35261. // ===================
  35262. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  35263. var ustep = 138 / 1024;
  35264. var vstep = 239 / 1024;
  35265. var uoffset = 60 / 1024;
  35266. var voffset = 26 / 1024;
  35267. // Second island should have margin, not to touch the first island
  35268. // avoid any borderline artefact in pixel rounding
  35269. var island_u_offset = -40 / 1024;
  35270. var island_v_offset = +20 / 1024;
  35271. // face is either island 0 or 1 :
  35272. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  35273. var island = [
  35274. 0, 0, 0, 0, 1,
  35275. 0, 0, 1, 1, 0,
  35276. 0, 0, 1, 1, 0,
  35277. 0, 1, 1, 1, 0 // 15 - 19
  35278. ];
  35279. var indices = new Array();
  35280. var positions = new Array();
  35281. var normals = new Array();
  35282. var uvs = new Array();
  35283. var current_indice = 0;
  35284. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  35285. var face_vertex_pos = new Array(3);
  35286. var face_vertex_uv = new Array(3);
  35287. var v012;
  35288. for (v012 = 0; v012 < 3; v012++) {
  35289. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  35290. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  35291. }
  35292. // create all with normals
  35293. for (var face = 0; face < 20; face++) {
  35294. // 3 vertex per face
  35295. for (v012 = 0; v012 < 3; v012++) {
  35296. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  35297. var v_id = ico_indices[3 * face + v012];
  35298. // vertex have 3D position (x,y,z)
  35299. 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]);
  35300. // Normalize to get normal, then scale to radius
  35301. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  35302. // uv Coordinates from vertex ID
  35303. 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);
  35304. }
  35305. // Subdivide the face (interpolate pos, norm, uv)
  35306. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  35307. // - norm is linear interpolation of vertex corner normal
  35308. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  35309. // - uv is linear interpolation
  35310. //
  35311. // Topology is as below for sub-divide by 2
  35312. // vertex shown as v0,v1,v2
  35313. // interp index is i1 to progress in range [v0,v1[
  35314. // interp index is i2 to progress in range [v0,v2[
  35315. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  35316. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  35317. //
  35318. //
  35319. // i2 v2
  35320. // ^ ^
  35321. // / / \
  35322. // / / \
  35323. // / / \
  35324. // / / (0,1) \
  35325. // / #---------\
  35326. // / / \ (0,0)'/ \
  35327. // / / \ / \
  35328. // / / \ / \
  35329. // / / (0,0) \ / (1,0) \
  35330. // / #---------#---------\
  35331. // v0 v1
  35332. //
  35333. // --------------------> i1
  35334. //
  35335. // interp of (i1,i2):
  35336. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  35337. // along i1 : lerp(x0,x1, i1/(S-i2))
  35338. //
  35339. // centroid of triangle is needed to get help normal computation
  35340. // (c1,c2) are used for centroid location
  35341. var interp_vertex = function (i1, i2, c1, c2) {
  35342. // vertex is interpolated from
  35343. // - face_vertex_pos[0..2]
  35344. // - face_vertex_uv[0..2]
  35345. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  35346. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  35347. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  35348. pos_interp.normalize();
  35349. var vertex_normal;
  35350. if (flat) {
  35351. // in flat mode, recalculate normal as face centroid normal
  35352. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  35353. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  35354. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  35355. }
  35356. else {
  35357. // in smooth mode, recalculate normal from each single vertex position
  35358. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  35359. }
  35360. // Vertex normal need correction due to X,Y,Z radius scaling
  35361. vertex_normal.x /= radiusX;
  35362. vertex_normal.y /= radiusY;
  35363. vertex_normal.z /= radiusZ;
  35364. vertex_normal.normalize();
  35365. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  35366. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  35367. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  35368. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  35369. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  35370. uvs.push(uv_interp.x, uv_interp.y);
  35371. // push each vertex has member of a face
  35372. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  35373. indices.push(current_indice);
  35374. current_indice++;
  35375. };
  35376. for (var i2 = 0; i2 < subdivisions; i2++) {
  35377. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  35378. // face : (i1,i2) for /\ :
  35379. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  35380. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  35381. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  35382. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  35383. if (i1 + i2 + 1 < subdivisions) {
  35384. // face : (i1,i2)' for \/ :
  35385. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  35386. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  35387. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  35388. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  35389. }
  35390. }
  35391. }
  35392. }
  35393. // Sides
  35394. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35395. // Result
  35396. var vertexData = new VertexData();
  35397. vertexData.indices = indices;
  35398. vertexData.positions = positions;
  35399. vertexData.normals = normals;
  35400. vertexData.uvs = uvs;
  35401. return vertexData;
  35402. };
  35403. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  35404. /**
  35405. * Creates the VertexData of the Polyhedron.
  35406. */
  35407. VertexData.CreatePolyhedron = function (options) {
  35408. // provided polyhedron types :
  35409. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  35410. // 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)
  35411. var polyhedra = [];
  35412. 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]] };
  35413. 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]] };
  35414. polyhedra[2] = {
  35415. 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]],
  35416. 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]]
  35417. };
  35418. polyhedra[3] = {
  35419. 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]],
  35420. 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]]
  35421. };
  35422. polyhedra[4] = {
  35423. 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]],
  35424. 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]]
  35425. };
  35426. 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]] };
  35427. 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]] };
  35428. 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]] };
  35429. 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]] };
  35430. 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]] };
  35431. 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]] };
  35432. 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]] };
  35433. 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]] };
  35434. 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]] };
  35435. polyhedra[14] = {
  35436. 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]],
  35437. 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]]
  35438. };
  35439. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  35440. var size = options.size;
  35441. var sizeX = options.sizeX || size || 1;
  35442. var sizeY = options.sizeY || size || 1;
  35443. var sizeZ = options.sizeZ || size || 1;
  35444. var data = options.custom || polyhedra[type];
  35445. var nbfaces = data.face.length;
  35446. var faceUV = options.faceUV || new Array(nbfaces);
  35447. var faceColors = options.faceColors;
  35448. var flat = (options.flat === undefined) ? true : options.flat;
  35449. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35450. var positions = new Array();
  35451. var indices = new Array();
  35452. var normals = new Array();
  35453. var uvs = new Array();
  35454. var colors = new Array();
  35455. var index = 0;
  35456. var faceIdx = 0; // face cursor in the array "indexes"
  35457. var indexes = new Array();
  35458. var i = 0;
  35459. var f = 0;
  35460. var u, v, ang, x, y, tmp;
  35461. // default face colors and UV if undefined
  35462. if (flat) {
  35463. for (f = 0; f < nbfaces; f++) {
  35464. if (faceColors && faceColors[f] === undefined) {
  35465. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  35466. }
  35467. if (faceUV && faceUV[f] === undefined) {
  35468. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  35469. }
  35470. }
  35471. }
  35472. if (!flat) {
  35473. for (i = 0; i < data.vertex.length; i++) {
  35474. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  35475. uvs.push(0, 0);
  35476. }
  35477. for (f = 0; f < nbfaces; f++) {
  35478. for (i = 0; i < data.face[f].length - 2; i++) {
  35479. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  35480. }
  35481. }
  35482. }
  35483. else {
  35484. for (f = 0; f < nbfaces; f++) {
  35485. var fl = data.face[f].length; // number of vertices of the current face
  35486. ang = 2 * Math.PI / fl;
  35487. x = 0.5 * Math.tan(ang / 2);
  35488. y = 0.5;
  35489. // positions, uvs, colors
  35490. for (i = 0; i < fl; i++) {
  35491. // positions
  35492. 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);
  35493. indexes.push(index);
  35494. index++;
  35495. // uvs
  35496. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  35497. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  35498. uvs.push(u, v);
  35499. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  35500. y = x * Math.sin(ang) + y * Math.cos(ang);
  35501. x = tmp;
  35502. // colors
  35503. if (faceColors) {
  35504. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  35505. }
  35506. }
  35507. // indices from indexes
  35508. for (i = 0; i < fl - 2; i++) {
  35509. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  35510. }
  35511. faceIdx += fl;
  35512. }
  35513. }
  35514. VertexData.ComputeNormals(positions, indices, normals);
  35515. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35516. var vertexData = new VertexData();
  35517. vertexData.positions = positions;
  35518. vertexData.indices = indices;
  35519. vertexData.normals = normals;
  35520. vertexData.uvs = uvs;
  35521. if (faceColors && flat) {
  35522. vertexData.colors = colors;
  35523. }
  35524. return vertexData;
  35525. };
  35526. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  35527. /**
  35528. * Creates the VertexData of the Torus Knot.
  35529. */
  35530. VertexData.CreateTorusKnot = function (options) {
  35531. var indices = new Array();
  35532. var positions = new Array();
  35533. var normals = new Array();
  35534. var uvs = new Array();
  35535. var radius = options.radius || 2;
  35536. var tube = options.tube || 0.5;
  35537. var radialSegments = options.radialSegments || 32;
  35538. var tubularSegments = options.tubularSegments || 32;
  35539. var p = options.p || 2;
  35540. var q = options.q || 3;
  35541. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35542. // Helper
  35543. var getPos = function (angle) {
  35544. var cu = Math.cos(angle);
  35545. var su = Math.sin(angle);
  35546. var quOverP = q / p * angle;
  35547. var cs = Math.cos(quOverP);
  35548. var tx = radius * (2 + cs) * 0.5 * cu;
  35549. var ty = radius * (2 + cs) * su * 0.5;
  35550. var tz = radius * Math.sin(quOverP) * 0.5;
  35551. return new BABYLON.Vector3(tx, ty, tz);
  35552. };
  35553. // Vertices
  35554. var i;
  35555. var j;
  35556. for (i = 0; i <= radialSegments; i++) {
  35557. var modI = i % radialSegments;
  35558. var u = modI / radialSegments * 2 * p * Math.PI;
  35559. var p1 = getPos(u);
  35560. var p2 = getPos(u + 0.01);
  35561. var tang = p2.subtract(p1);
  35562. var n = p2.add(p1);
  35563. var bitan = BABYLON.Vector3.Cross(tang, n);
  35564. n = BABYLON.Vector3.Cross(bitan, tang);
  35565. bitan.normalize();
  35566. n.normalize();
  35567. for (j = 0; j < tubularSegments; j++) {
  35568. var modJ = j % tubularSegments;
  35569. var v = modJ / tubularSegments * 2 * Math.PI;
  35570. var cx = -tube * Math.cos(v);
  35571. var cy = tube * Math.sin(v);
  35572. positions.push(p1.x + cx * n.x + cy * bitan.x);
  35573. positions.push(p1.y + cx * n.y + cy * bitan.y);
  35574. positions.push(p1.z + cx * n.z + cy * bitan.z);
  35575. uvs.push(i / radialSegments);
  35576. uvs.push(j / tubularSegments);
  35577. }
  35578. }
  35579. for (i = 0; i < radialSegments; i++) {
  35580. for (j = 0; j < tubularSegments; j++) {
  35581. var jNext = (j + 1) % tubularSegments;
  35582. var a = i * tubularSegments + j;
  35583. var b = (i + 1) * tubularSegments + j;
  35584. var c = (i + 1) * tubularSegments + jNext;
  35585. var d = i * tubularSegments + jNext;
  35586. indices.push(d);
  35587. indices.push(b);
  35588. indices.push(a);
  35589. indices.push(d);
  35590. indices.push(c);
  35591. indices.push(b);
  35592. }
  35593. }
  35594. // Normals
  35595. VertexData.ComputeNormals(positions, indices, normals);
  35596. // Sides
  35597. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  35598. // Result
  35599. var vertexData = new VertexData();
  35600. vertexData.indices = indices;
  35601. vertexData.positions = positions;
  35602. vertexData.normals = normals;
  35603. vertexData.uvs = uvs;
  35604. return vertexData;
  35605. };
  35606. // Tools
  35607. /**
  35608. * @param {any} - positions (number[] or Float32Array)
  35609. * @param {any} - indices (number[] or Uint16Array)
  35610. * @param {any} - normals (number[] or Float32Array)
  35611. * options (optional) :
  35612. * facetPositions : optional array of facet positions (vector3)
  35613. * facetNormals : optional array of facet normals (vector3)
  35614. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  35615. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  35616. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  35617. * bbSize : optional bounding box size data, required for facetPartitioning computation
  35618. * bInfo : optional bounding info, required for facetPartitioning computation
  35619. * useRightHandedSystem: optional boolean to for right handed system computation
  35620. * depthSort : optional boolean to enable the facet depth sort computation
  35621. * distanceTo : optional Vector3 to compute the facet depth from this location
  35622. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  35623. */
  35624. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  35625. // temporary scalar variables
  35626. var index = 0; // facet index
  35627. var p1p2x = 0.0; // p1p2 vector x coordinate
  35628. var p1p2y = 0.0; // p1p2 vector y coordinate
  35629. var p1p2z = 0.0; // p1p2 vector z coordinate
  35630. var p3p2x = 0.0; // p3p2 vector x coordinate
  35631. var p3p2y = 0.0; // p3p2 vector y coordinate
  35632. var p3p2z = 0.0; // p3p2 vector z coordinate
  35633. var faceNormalx = 0.0; // facet normal x coordinate
  35634. var faceNormaly = 0.0; // facet normal y coordinate
  35635. var faceNormalz = 0.0; // facet normal z coordinate
  35636. var length = 0.0; // facet normal length before normalization
  35637. var v1x = 0; // vector1 x index in the positions array
  35638. var v1y = 0; // vector1 y index in the positions array
  35639. var v1z = 0; // vector1 z index in the positions array
  35640. var v2x = 0; // vector2 x index in the positions array
  35641. var v2y = 0; // vector2 y index in the positions array
  35642. var v2z = 0; // vector2 z index in the positions array
  35643. var v3x = 0; // vector3 x index in the positions array
  35644. var v3y = 0; // vector3 y index in the positions array
  35645. var v3z = 0; // vector3 z index in the positions array
  35646. var computeFacetNormals = false;
  35647. var computeFacetPositions = false;
  35648. var computeFacetPartitioning = false;
  35649. var computeDepthSort = false;
  35650. var faceNormalSign = 1;
  35651. var ratio = 0;
  35652. var distanceTo = null;
  35653. if (options) {
  35654. computeFacetNormals = (options.facetNormals) ? true : false;
  35655. computeFacetPositions = (options.facetPositions) ? true : false;
  35656. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  35657. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  35658. ratio = options.ratio || 0;
  35659. computeDepthSort = (options.depthSort) ? true : false;
  35660. distanceTo = (options.distanceTo);
  35661. if (computeDepthSort) {
  35662. if (distanceTo === undefined) {
  35663. distanceTo = BABYLON.Vector3.Zero();
  35664. }
  35665. var depthSortedFacets = options.depthSortedFacets;
  35666. }
  35667. }
  35668. // facetPartitioning reinit if needed
  35669. var xSubRatio = 0;
  35670. var ySubRatio = 0;
  35671. var zSubRatio = 0;
  35672. var subSq = 0;
  35673. if (computeFacetPartitioning && options && options.bbSize) {
  35674. var ox = 0; // X partitioning index for facet position
  35675. var oy = 0; // Y partinioning index for facet position
  35676. var oz = 0; // Z partinioning index for facet position
  35677. var b1x = 0; // X partitioning index for facet v1 vertex
  35678. var b1y = 0; // Y partitioning index for facet v1 vertex
  35679. var b1z = 0; // z partitioning index for facet v1 vertex
  35680. var b2x = 0; // X partitioning index for facet v2 vertex
  35681. var b2y = 0; // Y partitioning index for facet v2 vertex
  35682. var b2z = 0; // Z partitioning index for facet v2 vertex
  35683. var b3x = 0; // X partitioning index for facet v3 vertex
  35684. var b3y = 0; // Y partitioning index for facet v3 vertex
  35685. var b3z = 0; // Z partitioning index for facet v3 vertex
  35686. var block_idx_o = 0; // facet barycenter block index
  35687. var block_idx_v1 = 0; // v1 vertex block index
  35688. var block_idx_v2 = 0; // v2 vertex block index
  35689. var block_idx_v3 = 0; // v3 vertex block index
  35690. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  35691. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  35692. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  35693. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  35694. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  35695. subSq = options.subDiv.max * options.subDiv.max;
  35696. options.facetPartitioning.length = 0;
  35697. }
  35698. // reset the normals
  35699. for (index = 0; index < positions.length; index++) {
  35700. normals[index] = 0.0;
  35701. }
  35702. // Loop : 1 indice triplet = 1 facet
  35703. var nbFaces = (indices.length / 3) | 0;
  35704. for (index = 0; index < nbFaces; index++) {
  35705. // get the indexes of the coordinates of each vertex of the facet
  35706. v1x = indices[index * 3] * 3;
  35707. v1y = v1x + 1;
  35708. v1z = v1x + 2;
  35709. v2x = indices[index * 3 + 1] * 3;
  35710. v2y = v2x + 1;
  35711. v2z = v2x + 2;
  35712. v3x = indices[index * 3 + 2] * 3;
  35713. v3y = v3x + 1;
  35714. v3z = v3x + 2;
  35715. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  35716. p1p2y = positions[v1y] - positions[v2y];
  35717. p1p2z = positions[v1z] - positions[v2z];
  35718. p3p2x = positions[v3x] - positions[v2x];
  35719. p3p2y = positions[v3y] - positions[v2y];
  35720. p3p2z = positions[v3z] - positions[v2z];
  35721. // compute the face normal with the cross product
  35722. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  35723. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  35724. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  35725. // normalize this normal and store it in the array facetData
  35726. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35727. length = (length === 0) ? 1.0 : length;
  35728. faceNormalx /= length;
  35729. faceNormaly /= length;
  35730. faceNormalz /= length;
  35731. if (computeFacetNormals && options) {
  35732. options.facetNormals[index].x = faceNormalx;
  35733. options.facetNormals[index].y = faceNormaly;
  35734. options.facetNormals[index].z = faceNormalz;
  35735. }
  35736. if (computeFacetPositions && options) {
  35737. // compute and the facet barycenter coordinates in the array facetPositions
  35738. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35739. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35740. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35741. }
  35742. if (computeFacetPartitioning && options) {
  35743. // store the facet indexes in arrays in the main facetPartitioning array :
  35744. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35745. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  35746. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  35747. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  35748. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35749. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35750. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35751. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35752. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35753. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35754. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  35755. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  35756. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  35757. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35758. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35759. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35760. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35761. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35762. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35763. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35764. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35765. // push each facet index in each block containing the vertex
  35766. options.facetPartitioning[block_idx_v1].push(index);
  35767. if (block_idx_v2 != block_idx_v1) {
  35768. options.facetPartitioning[block_idx_v2].push(index);
  35769. }
  35770. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35771. options.facetPartitioning[block_idx_v3].push(index);
  35772. }
  35773. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35774. options.facetPartitioning[block_idx_o].push(index);
  35775. }
  35776. }
  35777. if (computeDepthSort && options && options.facetPositions) {
  35778. var dsf = depthSortedFacets[index];
  35779. dsf.ind = index * 3;
  35780. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  35781. }
  35782. // compute the normals anyway
  35783. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35784. normals[v1y] += faceNormaly;
  35785. normals[v1z] += faceNormalz;
  35786. normals[v2x] += faceNormalx;
  35787. normals[v2y] += faceNormaly;
  35788. normals[v2z] += faceNormalz;
  35789. normals[v3x] += faceNormalx;
  35790. normals[v3y] += faceNormaly;
  35791. normals[v3z] += faceNormalz;
  35792. }
  35793. // last normalization of each normal
  35794. for (index = 0; index < normals.length / 3; index++) {
  35795. faceNormalx = normals[index * 3];
  35796. faceNormaly = normals[index * 3 + 1];
  35797. faceNormalz = normals[index * 3 + 2];
  35798. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35799. length = (length === 0) ? 1.0 : length;
  35800. faceNormalx /= length;
  35801. faceNormaly /= length;
  35802. faceNormalz /= length;
  35803. normals[index * 3] = faceNormalx;
  35804. normals[index * 3 + 1] = faceNormaly;
  35805. normals[index * 3 + 2] = faceNormalz;
  35806. }
  35807. };
  35808. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35809. var li = indices.length;
  35810. var ln = normals.length;
  35811. var i;
  35812. var n;
  35813. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35814. switch (sideOrientation) {
  35815. case BABYLON.Mesh.FRONTSIDE:
  35816. // nothing changed
  35817. break;
  35818. case BABYLON.Mesh.BACKSIDE:
  35819. var tmp;
  35820. // indices
  35821. for (i = 0; i < li; i += 3) {
  35822. tmp = indices[i];
  35823. indices[i] = indices[i + 2];
  35824. indices[i + 2] = tmp;
  35825. }
  35826. // normals
  35827. for (n = 0; n < ln; n++) {
  35828. normals[n] = -normals[n];
  35829. }
  35830. break;
  35831. case BABYLON.Mesh.DOUBLESIDE:
  35832. // positions
  35833. var lp = positions.length;
  35834. var l = lp / 3;
  35835. for (var p = 0; p < lp; p++) {
  35836. positions[lp + p] = positions[p];
  35837. }
  35838. // indices
  35839. for (i = 0; i < li; i += 3) {
  35840. indices[i + li] = indices[i + 2] + l;
  35841. indices[i + 1 + li] = indices[i + 1] + l;
  35842. indices[i + 2 + li] = indices[i] + l;
  35843. }
  35844. // normals
  35845. for (n = 0; n < ln; n++) {
  35846. normals[ln + n] = -normals[n];
  35847. }
  35848. // uvs
  35849. var lu = uvs.length;
  35850. var u = 0;
  35851. for (u = 0; u < lu; u++) {
  35852. uvs[u + lu] = uvs[u];
  35853. }
  35854. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35855. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35856. u = 0;
  35857. for (i = 0; i < lu / 2; i++) {
  35858. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35859. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35860. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35861. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35862. u += 2;
  35863. }
  35864. break;
  35865. }
  35866. };
  35867. /**
  35868. * Creates a new VertexData from the imported parameters.
  35869. */
  35870. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35871. var vertexData = new VertexData();
  35872. // positions
  35873. var positions = parsedVertexData.positions;
  35874. if (positions) {
  35875. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35876. }
  35877. // normals
  35878. var normals = parsedVertexData.normals;
  35879. if (normals) {
  35880. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35881. }
  35882. // tangents
  35883. var tangents = parsedVertexData.tangents;
  35884. if (tangents) {
  35885. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35886. }
  35887. // uvs
  35888. var uvs = parsedVertexData.uvs;
  35889. if (uvs) {
  35890. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35891. }
  35892. // uv2s
  35893. var uv2s = parsedVertexData.uv2s;
  35894. if (uv2s) {
  35895. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35896. }
  35897. // uv3s
  35898. var uv3s = parsedVertexData.uv3s;
  35899. if (uv3s) {
  35900. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35901. }
  35902. // uv4s
  35903. var uv4s = parsedVertexData.uv4s;
  35904. if (uv4s) {
  35905. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35906. }
  35907. // uv5s
  35908. var uv5s = parsedVertexData.uv5s;
  35909. if (uv5s) {
  35910. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35911. }
  35912. // uv6s
  35913. var uv6s = parsedVertexData.uv6s;
  35914. if (uv6s) {
  35915. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35916. }
  35917. // colors
  35918. var colors = parsedVertexData.colors;
  35919. if (colors) {
  35920. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35921. }
  35922. // matricesIndices
  35923. var matricesIndices = parsedVertexData.matricesIndices;
  35924. if (matricesIndices) {
  35925. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35926. }
  35927. // matricesWeights
  35928. var matricesWeights = parsedVertexData.matricesWeights;
  35929. if (matricesWeights) {
  35930. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35931. }
  35932. // indices
  35933. var indices = parsedVertexData.indices;
  35934. if (indices) {
  35935. vertexData.indices = indices;
  35936. }
  35937. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35938. };
  35939. return VertexData;
  35940. }());
  35941. BABYLON.VertexData = VertexData;
  35942. })(BABYLON || (BABYLON = {}));
  35943. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35944. "use strict";
  35945. var BABYLON;
  35946. (function (BABYLON) {
  35947. /**
  35948. * Class used to store geometry data (vertex buffers + index buffer)
  35949. */
  35950. var Geometry = /** @class */ (function () {
  35951. /**
  35952. * Creates a new geometry
  35953. * @param id defines the unique ID
  35954. * @param scene defines the hosting scene
  35955. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35956. * @param updatable defines if geometry must be updatable (false by default)
  35957. * @param mesh defines the mesh that will be associated with the geometry
  35958. */
  35959. function Geometry(id, scene, vertexData, updatable, mesh) {
  35960. if (updatable === void 0) { updatable = false; }
  35961. if (mesh === void 0) { mesh = null; }
  35962. /**
  35963. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35964. */
  35965. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35966. this._totalVertices = 0;
  35967. this._isDisposed = false;
  35968. this._indexBufferIsUpdatable = false;
  35969. this.id = id;
  35970. this._engine = scene.getEngine();
  35971. this._meshes = [];
  35972. this._scene = scene;
  35973. //Init vertex buffer cache
  35974. this._vertexBuffers = {};
  35975. this._indices = [];
  35976. this._updatable = updatable;
  35977. // vertexData
  35978. if (vertexData) {
  35979. this.setAllVerticesData(vertexData, updatable);
  35980. }
  35981. else {
  35982. this._totalVertices = 0;
  35983. this._indices = [];
  35984. }
  35985. if (this._engine.getCaps().vertexArrayObject) {
  35986. this._vertexArrayObjects = {};
  35987. }
  35988. // applyToMesh
  35989. if (mesh) {
  35990. if (mesh.getClassName() === "LinesMesh") {
  35991. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35992. this.updateExtend();
  35993. }
  35994. this.applyToMesh(mesh);
  35995. mesh.computeWorldMatrix(true);
  35996. }
  35997. }
  35998. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35999. /**
  36000. * 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
  36001. */
  36002. get: function () {
  36003. return this._boundingBias;
  36004. },
  36005. /**
  36006. * 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
  36007. */
  36008. set: function (value) {
  36009. if (this._boundingBias && this._boundingBias.equals(value)) {
  36010. return;
  36011. }
  36012. this._boundingBias = value.clone();
  36013. this.updateBoundingInfo(true, null);
  36014. },
  36015. enumerable: true,
  36016. configurable: true
  36017. });
  36018. /**
  36019. * Static function used to attach a new empty geometry to a mesh
  36020. * @param mesh defines the mesh to attach the geometry to
  36021. * @returns the new {BABYLON.Geometry}
  36022. */
  36023. Geometry.CreateGeometryForMesh = function (mesh) {
  36024. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  36025. geometry.applyToMesh(mesh);
  36026. return geometry;
  36027. };
  36028. Object.defineProperty(Geometry.prototype, "extend", {
  36029. /**
  36030. * Gets the current extend of the geometry
  36031. */
  36032. get: function () {
  36033. return this._extend;
  36034. },
  36035. enumerable: true,
  36036. configurable: true
  36037. });
  36038. /**
  36039. * Gets the hosting scene
  36040. * @returns the hosting {BABYLON.Scene}
  36041. */
  36042. Geometry.prototype.getScene = function () {
  36043. return this._scene;
  36044. };
  36045. /**
  36046. * Gets the hosting engine
  36047. * @returns the hosting {BABYLON.Engine}
  36048. */
  36049. Geometry.prototype.getEngine = function () {
  36050. return this._engine;
  36051. };
  36052. /**
  36053. * Defines if the geometry is ready to use
  36054. * @returns true if the geometry is ready to be used
  36055. */
  36056. Geometry.prototype.isReady = function () {
  36057. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36058. };
  36059. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36060. /**
  36061. * Gets a value indicating that the geometry should not be serialized
  36062. */
  36063. get: function () {
  36064. for (var index = 0; index < this._meshes.length; index++) {
  36065. if (!this._meshes[index].doNotSerialize) {
  36066. return false;
  36067. }
  36068. }
  36069. return true;
  36070. },
  36071. enumerable: true,
  36072. configurable: true
  36073. });
  36074. /** @ignore */
  36075. Geometry.prototype._rebuild = function () {
  36076. if (this._vertexArrayObjects) {
  36077. this._vertexArrayObjects = {};
  36078. }
  36079. // Index buffer
  36080. if (this._meshes.length !== 0 && this._indices) {
  36081. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36082. }
  36083. // Vertex buffers
  36084. for (var key in this._vertexBuffers) {
  36085. var vertexBuffer = this._vertexBuffers[key];
  36086. vertexBuffer._rebuild();
  36087. }
  36088. };
  36089. /**
  36090. * Affects all gemetry data in one call
  36091. * @param vertexData defines the geometry data
  36092. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  36093. */
  36094. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36095. vertexData.applyToGeometry(this, updatable);
  36096. this.notifyUpdate();
  36097. };
  36098. /**
  36099. * Set specific vertex data
  36100. * @param kind defines the data kind (Position, normal, etc...)
  36101. * @param data defines the vertex data to use
  36102. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  36103. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  36104. */
  36105. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36106. if (updatable === void 0) { updatable = false; }
  36107. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36108. this.setVerticesBuffer(buffer);
  36109. };
  36110. /**
  36111. * Removes a specific vertex data
  36112. * @param kind defines the data kind (Position, normal, etc...)
  36113. */
  36114. Geometry.prototype.removeVerticesData = function (kind) {
  36115. if (this._vertexBuffers[kind]) {
  36116. this._vertexBuffers[kind].dispose();
  36117. delete this._vertexBuffers[kind];
  36118. }
  36119. };
  36120. /**
  36121. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  36122. * @param buffer defines the vertex buffer to use
  36123. */
  36124. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36125. var kind = buffer.getKind();
  36126. if (this._vertexBuffers[kind]) {
  36127. this._vertexBuffers[kind].dispose();
  36128. }
  36129. this._vertexBuffers[kind] = buffer;
  36130. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36131. var data = buffer.getData();
  36132. var stride = buffer.getStrideSize();
  36133. this._totalVertices = data.length / stride;
  36134. this.updateExtend(data, stride);
  36135. this._resetPointsArrayCache();
  36136. var meshes = this._meshes;
  36137. var numOfMeshes = meshes.length;
  36138. for (var index = 0; index < numOfMeshes; index++) {
  36139. var mesh = meshes[index];
  36140. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36141. mesh._createGlobalSubMesh(false);
  36142. mesh.computeWorldMatrix(true);
  36143. }
  36144. }
  36145. this.notifyUpdate(kind);
  36146. if (this._vertexArrayObjects) {
  36147. this._disposeVertexArrayObjects();
  36148. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  36149. }
  36150. };
  36151. /**
  36152. * Update a specific vertex buffer
  36153. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  36154. * It will do nothing if the buffer is not updatable
  36155. * @param kind defines the data kind (Position, normal, etc...)
  36156. * @param data defines the data to use
  36157. * @param offset defines the offset in the target buffer where to store the data
  36158. */
  36159. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36160. var vertexBuffer = this.getVertexBuffer(kind);
  36161. if (!vertexBuffer) {
  36162. return;
  36163. }
  36164. vertexBuffer.updateDirectly(data, offset);
  36165. this.notifyUpdate(kind);
  36166. };
  36167. /**
  36168. * Update a specific vertex buffer
  36169. * This function will create a new buffer if the current one is not updatable
  36170. * @param kind defines the data kind (Position, normal, etc...)
  36171. * @param data defines the data to use
  36172. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  36173. */
  36174. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36175. if (updateExtends === void 0) { updateExtends = false; }
  36176. var vertexBuffer = this.getVertexBuffer(kind);
  36177. if (!vertexBuffer) {
  36178. return;
  36179. }
  36180. vertexBuffer.update(data);
  36181. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36182. var stride = vertexBuffer.getStrideSize();
  36183. this._totalVertices = data.length / stride;
  36184. this.updateBoundingInfo(updateExtends, data);
  36185. }
  36186. this.notifyUpdate(kind);
  36187. };
  36188. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36189. if (updateExtends) {
  36190. this.updateExtend(data);
  36191. }
  36192. var meshes = this._meshes;
  36193. var numOfMeshes = meshes.length;
  36194. this._resetPointsArrayCache();
  36195. for (var index = 0; index < numOfMeshes; index++) {
  36196. var mesh = meshes[index];
  36197. if (updateExtends) {
  36198. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36199. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36200. var subMesh = mesh.subMeshes[subIndex];
  36201. subMesh.refreshBoundingInfo();
  36202. }
  36203. }
  36204. }
  36205. };
  36206. /** @ignore */
  36207. Geometry.prototype._bind = function (effect, indexToBind) {
  36208. if (!effect) {
  36209. return;
  36210. }
  36211. if (indexToBind === undefined) {
  36212. indexToBind = this._indexBuffer;
  36213. }
  36214. var vbs = this.getVertexBuffers();
  36215. if (!vbs) {
  36216. return;
  36217. }
  36218. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  36219. this._engine.bindBuffers(vbs, indexToBind, effect);
  36220. return;
  36221. }
  36222. // Using VAO
  36223. if (!this._vertexArrayObjects[effect.key]) {
  36224. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  36225. }
  36226. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  36227. };
  36228. /**
  36229. * Gets total number of vertices
  36230. * @returns the total number of vertices
  36231. */
  36232. Geometry.prototype.getTotalVertices = function () {
  36233. if (!this.isReady()) {
  36234. return 0;
  36235. }
  36236. return this._totalVertices;
  36237. };
  36238. /**
  36239. * Gets a specific vertex data attached to this geometry
  36240. * @param kind defines the data kind (Position, normal, etc...)
  36241. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  36242. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  36243. * @returns a float array containing vertex data
  36244. */
  36245. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  36246. var vertexBuffer = this.getVertexBuffer(kind);
  36247. if (!vertexBuffer) {
  36248. return null;
  36249. }
  36250. var orig = vertexBuffer.getData();
  36251. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  36252. return orig;
  36253. }
  36254. else {
  36255. var len = orig.length;
  36256. var copy = [];
  36257. for (var i = 0; i < len; i++) {
  36258. copy.push(orig[i]);
  36259. }
  36260. return copy;
  36261. }
  36262. };
  36263. /**
  36264. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  36265. * @param kind defines the data kind (Position, normal, etc...)
  36266. * @returns true if the vertex buffer with the specified kind is updatable
  36267. */
  36268. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  36269. var vb = this._vertexBuffers[kind];
  36270. if (!vb) {
  36271. return false;
  36272. }
  36273. return vb.isUpdatable();
  36274. };
  36275. /**
  36276. * Gets a specific vertex buffer
  36277. * @param kind defines the data kind (Position, normal, etc...)
  36278. * @returns a {BABYLON.VertexBuffer}
  36279. */
  36280. Geometry.prototype.getVertexBuffer = function (kind) {
  36281. if (!this.isReady()) {
  36282. return null;
  36283. }
  36284. return this._vertexBuffers[kind];
  36285. };
  36286. /**
  36287. * Returns all vertex buffers
  36288. * @return an object holding all vertex buffers indexed by kind
  36289. */
  36290. Geometry.prototype.getVertexBuffers = function () {
  36291. if (!this.isReady()) {
  36292. return null;
  36293. }
  36294. return this._vertexBuffers;
  36295. };
  36296. /**
  36297. * Gets a boolean indicating if specific vertex buffer is present
  36298. * @param kind defines the data kind (Position, normal, etc...)
  36299. * @returns true if data is present
  36300. */
  36301. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36302. if (!this._vertexBuffers) {
  36303. if (this._delayInfo) {
  36304. return this._delayInfo.indexOf(kind) !== -1;
  36305. }
  36306. return false;
  36307. }
  36308. return this._vertexBuffers[kind] !== undefined;
  36309. };
  36310. /**
  36311. * Gets a list of all attached data kinds (Position, normal, etc...)
  36312. * @returns a list of string containing all kinds
  36313. */
  36314. Geometry.prototype.getVerticesDataKinds = function () {
  36315. var result = [];
  36316. var kind;
  36317. if (!this._vertexBuffers && this._delayInfo) {
  36318. for (kind in this._delayInfo) {
  36319. result.push(kind);
  36320. }
  36321. }
  36322. else {
  36323. for (kind in this._vertexBuffers) {
  36324. result.push(kind);
  36325. }
  36326. }
  36327. return result;
  36328. };
  36329. /**
  36330. * Update index buffer
  36331. * @param indices defines the indices to store in the index buffer
  36332. * @param offset defines the offset in the target buffer where to store the data
  36333. */
  36334. Geometry.prototype.updateIndices = function (indices, offset) {
  36335. if (!this._indexBuffer) {
  36336. return;
  36337. }
  36338. if (!this._indexBufferIsUpdatable) {
  36339. this.setIndices(indices, null, true);
  36340. }
  36341. else {
  36342. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  36343. }
  36344. };
  36345. /**
  36346. * Creates a new index buffer
  36347. * @param indices defines the indices to store in the index buffer
  36348. * @param totalVertices defines the total number of vertices (could be null)
  36349. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  36350. */
  36351. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  36352. if (totalVertices === void 0) { totalVertices = null; }
  36353. if (updatable === void 0) { updatable = false; }
  36354. if (this._indexBuffer) {
  36355. this._engine._releaseBuffer(this._indexBuffer);
  36356. }
  36357. this._disposeVertexArrayObjects();
  36358. this._indices = indices;
  36359. this._indexBufferIsUpdatable = updatable;
  36360. if (this._meshes.length !== 0 && this._indices) {
  36361. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  36362. }
  36363. if (totalVertices != undefined) {
  36364. this._totalVertices = totalVertices;
  36365. }
  36366. var meshes = this._meshes;
  36367. var numOfMeshes = meshes.length;
  36368. for (var index = 0; index < numOfMeshes; index++) {
  36369. meshes[index]._createGlobalSubMesh(true);
  36370. }
  36371. this.notifyUpdate();
  36372. };
  36373. /**
  36374. * Return the total number of indices
  36375. * @returns the total number of indices
  36376. */
  36377. Geometry.prototype.getTotalIndices = function () {
  36378. if (!this.isReady()) {
  36379. return 0;
  36380. }
  36381. return this._indices.length;
  36382. };
  36383. /**
  36384. * Gets the index buffer array
  36385. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  36386. * @returns the index buffer array
  36387. */
  36388. Geometry.prototype.getIndices = function (copyWhenShared) {
  36389. if (!this.isReady()) {
  36390. return null;
  36391. }
  36392. var orig = this._indices;
  36393. if (!copyWhenShared || this._meshes.length === 1) {
  36394. return orig;
  36395. }
  36396. else {
  36397. var len = orig.length;
  36398. var copy = [];
  36399. for (var i = 0; i < len; i++) {
  36400. copy.push(orig[i]);
  36401. }
  36402. return copy;
  36403. }
  36404. };
  36405. /**
  36406. * Gets the index buffer
  36407. * @return the index buffer
  36408. */
  36409. Geometry.prototype.getIndexBuffer = function () {
  36410. if (!this.isReady()) {
  36411. return null;
  36412. }
  36413. return this._indexBuffer;
  36414. };
  36415. /** @ignore */
  36416. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  36417. if (effect === void 0) { effect = null; }
  36418. if (!effect || !this._vertexArrayObjects) {
  36419. return;
  36420. }
  36421. if (this._vertexArrayObjects[effect.key]) {
  36422. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  36423. delete this._vertexArrayObjects[effect.key];
  36424. }
  36425. };
  36426. /**
  36427. * Release the associated resources for a specific mesh
  36428. * @param mesh defines the source mesh
  36429. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  36430. */
  36431. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36432. var meshes = this._meshes;
  36433. var index = meshes.indexOf(mesh);
  36434. if (index === -1) {
  36435. return;
  36436. }
  36437. meshes.splice(index, 1);
  36438. mesh._geometry = null;
  36439. if (meshes.length === 0 && shouldDispose) {
  36440. this.dispose();
  36441. }
  36442. };
  36443. /**
  36444. * Apply current geometry to a given mesh
  36445. * @param mesh defines the mesh to apply geometry to
  36446. */
  36447. Geometry.prototype.applyToMesh = function (mesh) {
  36448. if (mesh._geometry === this) {
  36449. return;
  36450. }
  36451. var previousGeometry = mesh._geometry;
  36452. if (previousGeometry) {
  36453. previousGeometry.releaseForMesh(mesh);
  36454. }
  36455. var meshes = this._meshes;
  36456. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36457. mesh._geometry = this;
  36458. this._scene.pushGeometry(this);
  36459. meshes.push(mesh);
  36460. if (this.isReady()) {
  36461. this._applyToMesh(mesh);
  36462. }
  36463. else {
  36464. mesh._boundingInfo = this._boundingInfo;
  36465. }
  36466. };
  36467. Geometry.prototype.updateExtend = function (data, stride) {
  36468. if (data === void 0) { data = null; }
  36469. if (!data) {
  36470. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36471. }
  36472. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36473. };
  36474. Geometry.prototype._applyToMesh = function (mesh) {
  36475. var numOfMeshes = this._meshes.length;
  36476. // vertexBuffers
  36477. for (var kind in this._vertexBuffers) {
  36478. if (numOfMeshes === 1) {
  36479. this._vertexBuffers[kind].create();
  36480. }
  36481. var buffer = this._vertexBuffers[kind].getBuffer();
  36482. if (buffer)
  36483. buffer.references = numOfMeshes;
  36484. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36485. if (!this._extend) {
  36486. this.updateExtend(this._vertexBuffers[kind].getData());
  36487. }
  36488. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36489. mesh._createGlobalSubMesh(false);
  36490. //bounding info was just created again, world matrix should be applied again.
  36491. mesh._updateBoundingInfo();
  36492. }
  36493. }
  36494. // indexBuffer
  36495. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36496. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36497. }
  36498. if (this._indexBuffer) {
  36499. this._indexBuffer.references = numOfMeshes;
  36500. }
  36501. };
  36502. Geometry.prototype.notifyUpdate = function (kind) {
  36503. if (this.onGeometryUpdated) {
  36504. this.onGeometryUpdated(this, kind);
  36505. }
  36506. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  36507. var mesh = _a[_i];
  36508. mesh._markSubMeshesAsAttributesDirty();
  36509. }
  36510. };
  36511. /**
  36512. * Load the geometry if it was flagged as delay loaded
  36513. * @param scene defines the hosting scene
  36514. * @param onLoaded defines a callback called when the geometry is loaded
  36515. */
  36516. Geometry.prototype.load = function (scene, onLoaded) {
  36517. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36518. return;
  36519. }
  36520. if (this.isReady()) {
  36521. if (onLoaded) {
  36522. onLoaded();
  36523. }
  36524. return;
  36525. }
  36526. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36527. this._queueLoad(scene, onLoaded);
  36528. };
  36529. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36530. var _this = this;
  36531. if (!this.delayLoadingFile) {
  36532. return;
  36533. }
  36534. scene._addPendingData(this);
  36535. scene._loadFile(this.delayLoadingFile, function (data) {
  36536. if (!_this._delayLoadingFunction) {
  36537. return;
  36538. }
  36539. _this._delayLoadingFunction(JSON.parse(data), _this);
  36540. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36541. _this._delayInfo = [];
  36542. scene._removePendingData(_this);
  36543. var meshes = _this._meshes;
  36544. var numOfMeshes = meshes.length;
  36545. for (var index = 0; index < numOfMeshes; index++) {
  36546. _this._applyToMesh(meshes[index]);
  36547. }
  36548. if (onLoaded) {
  36549. onLoaded();
  36550. }
  36551. }, undefined, true);
  36552. };
  36553. /**
  36554. * Invert the geometry to move from a right handed system to a left handed one.
  36555. */
  36556. Geometry.prototype.toLeftHanded = function () {
  36557. // Flip faces
  36558. var tIndices = this.getIndices(false);
  36559. if (tIndices != null && tIndices.length > 0) {
  36560. for (var i = 0; i < tIndices.length; i += 3) {
  36561. var tTemp = tIndices[i + 0];
  36562. tIndices[i + 0] = tIndices[i + 2];
  36563. tIndices[i + 2] = tTemp;
  36564. }
  36565. this.setIndices(tIndices);
  36566. }
  36567. // Negate position.z
  36568. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36569. if (tPositions != null && tPositions.length > 0) {
  36570. for (var i = 0; i < tPositions.length; i += 3) {
  36571. tPositions[i + 2] = -tPositions[i + 2];
  36572. }
  36573. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36574. }
  36575. // Negate normal.z
  36576. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36577. if (tNormals != null && tNormals.length > 0) {
  36578. for (var i = 0; i < tNormals.length; i += 3) {
  36579. tNormals[i + 2] = -tNormals[i + 2];
  36580. }
  36581. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36582. }
  36583. };
  36584. // Cache
  36585. /** @ignore */
  36586. Geometry.prototype._resetPointsArrayCache = function () {
  36587. this._positions = null;
  36588. };
  36589. /** @ignore */
  36590. Geometry.prototype._generatePointsArray = function () {
  36591. if (this._positions)
  36592. return true;
  36593. this._positions = [];
  36594. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36595. if (!data) {
  36596. return false;
  36597. }
  36598. for (var index = 0; index < data.length; index += 3) {
  36599. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  36600. }
  36601. return true;
  36602. };
  36603. /**
  36604. * Gets a value indicating if the geometry is disposed
  36605. * @returns true if the geometry was disposed
  36606. */
  36607. Geometry.prototype.isDisposed = function () {
  36608. return this._isDisposed;
  36609. };
  36610. Geometry.prototype._disposeVertexArrayObjects = function () {
  36611. if (this._vertexArrayObjects) {
  36612. for (var kind in this._vertexArrayObjects) {
  36613. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  36614. }
  36615. this._vertexArrayObjects = {};
  36616. }
  36617. };
  36618. /**
  36619. * Free all associated resources
  36620. */
  36621. Geometry.prototype.dispose = function () {
  36622. var meshes = this._meshes;
  36623. var numOfMeshes = meshes.length;
  36624. var index;
  36625. for (index = 0; index < numOfMeshes; index++) {
  36626. this.releaseForMesh(meshes[index]);
  36627. }
  36628. this._meshes = [];
  36629. this._disposeVertexArrayObjects();
  36630. for (var kind in this._vertexBuffers) {
  36631. this._vertexBuffers[kind].dispose();
  36632. }
  36633. this._vertexBuffers = {};
  36634. this._totalVertices = 0;
  36635. if (this._indexBuffer) {
  36636. this._engine._releaseBuffer(this._indexBuffer);
  36637. }
  36638. this._indexBuffer = null;
  36639. this._indices = [];
  36640. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36641. this.delayLoadingFile = null;
  36642. this._delayLoadingFunction = null;
  36643. this._delayInfo = [];
  36644. this._boundingInfo = null;
  36645. this._scene.removeGeometry(this);
  36646. this._isDisposed = true;
  36647. };
  36648. /**
  36649. * Clone the current geometry into a new geometry
  36650. * @param id defines the unique ID of the new geometry
  36651. * @returns a new geometry object
  36652. */
  36653. Geometry.prototype.copy = function (id) {
  36654. var vertexData = new BABYLON.VertexData();
  36655. vertexData.indices = [];
  36656. var indices = this.getIndices();
  36657. if (indices) {
  36658. for (var index = 0; index < indices.length; index++) {
  36659. vertexData.indices.push(indices[index]);
  36660. }
  36661. }
  36662. var updatable = false;
  36663. var stopChecking = false;
  36664. var kind;
  36665. for (kind in this._vertexBuffers) {
  36666. // using slice() to make a copy of the array and not just reference it
  36667. var data = this.getVerticesData(kind);
  36668. if (data instanceof Float32Array) {
  36669. vertexData.set(new Float32Array(data), kind);
  36670. }
  36671. else {
  36672. vertexData.set(data.slice(0), kind);
  36673. }
  36674. if (!stopChecking) {
  36675. var vb = this.getVertexBuffer(kind);
  36676. if (vb) {
  36677. updatable = vb.isUpdatable();
  36678. stopChecking = !updatable;
  36679. }
  36680. }
  36681. }
  36682. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  36683. geometry.delayLoadState = this.delayLoadState;
  36684. geometry.delayLoadingFile = this.delayLoadingFile;
  36685. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36686. for (kind in this._delayInfo) {
  36687. geometry._delayInfo = geometry._delayInfo || [];
  36688. geometry._delayInfo.push(kind);
  36689. }
  36690. // Bounding info
  36691. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36692. return geometry;
  36693. };
  36694. /**
  36695. * Serialize the current geometry info (and not the vertices data) into a JSON object
  36696. * @return a JSON representation of the current geometry data (without the vertices data)
  36697. */
  36698. Geometry.prototype.serialize = function () {
  36699. var serializationObject = {};
  36700. serializationObject.id = this.id;
  36701. serializationObject.updatable = this._updatable;
  36702. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  36703. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36704. }
  36705. return serializationObject;
  36706. };
  36707. Geometry.prototype.toNumberArray = function (origin) {
  36708. if (Array.isArray(origin)) {
  36709. return origin;
  36710. }
  36711. else {
  36712. return Array.prototype.slice.call(origin);
  36713. }
  36714. };
  36715. /**
  36716. * Serialize all vertices data into a JSON oject
  36717. * @returns a JSON representation of the current geometry data
  36718. */
  36719. Geometry.prototype.serializeVerticeData = function () {
  36720. var serializationObject = this.serialize();
  36721. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36722. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  36723. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  36724. serializationObject.positions._updatable = true;
  36725. }
  36726. }
  36727. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36728. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  36729. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  36730. serializationObject.normals._updatable = true;
  36731. }
  36732. }
  36733. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36734. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  36735. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  36736. serializationObject.tangets._updatable = true;
  36737. }
  36738. }
  36739. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36740. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  36741. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  36742. serializationObject.uvs._updatable = true;
  36743. }
  36744. }
  36745. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36746. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  36747. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  36748. serializationObject.uv2s._updatable = true;
  36749. }
  36750. }
  36751. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36752. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  36753. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  36754. serializationObject.uv3s._updatable = true;
  36755. }
  36756. }
  36757. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36758. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  36759. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  36760. serializationObject.uv4s._updatable = true;
  36761. }
  36762. }
  36763. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36764. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  36765. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  36766. serializationObject.uv5s._updatable = true;
  36767. }
  36768. }
  36769. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36770. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  36771. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  36772. serializationObject.uv6s._updatable = true;
  36773. }
  36774. }
  36775. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36776. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  36777. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  36778. serializationObject.colors._updatable = true;
  36779. }
  36780. }
  36781. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36782. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  36783. serializationObject.matricesIndices._isExpanded = true;
  36784. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36785. serializationObject.matricesIndices._updatable = true;
  36786. }
  36787. }
  36788. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36789. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36790. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36791. serializationObject.matricesWeights._updatable = true;
  36792. }
  36793. }
  36794. serializationObject.indices = this.toNumberArray(this.getIndices());
  36795. return serializationObject;
  36796. };
  36797. // Statics
  36798. /**
  36799. * Extracts a clone of a mesh geometry
  36800. * @param mesh defines the source mesh
  36801. * @param id defines the unique ID of the new geometry object
  36802. * @returns the new geometry object
  36803. */
  36804. Geometry.ExtractFromMesh = function (mesh, id) {
  36805. var geometry = mesh._geometry;
  36806. if (!geometry) {
  36807. return null;
  36808. }
  36809. return geometry.copy(id);
  36810. };
  36811. /**
  36812. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36813. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36814. * Be aware Math.random() could cause collisions, but:
  36815. * "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"
  36816. * @returns a string containing a new GUID
  36817. */
  36818. Geometry.RandomId = function () {
  36819. return BABYLON.Tools.RandomId();
  36820. };
  36821. /** @ignore */
  36822. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36823. var scene = mesh.getScene();
  36824. // Geometry
  36825. var geometryId = parsedGeometry.geometryId;
  36826. if (geometryId) {
  36827. var geometry = scene.getGeometryByID(geometryId);
  36828. if (geometry) {
  36829. geometry.applyToMesh(mesh);
  36830. }
  36831. }
  36832. else if (parsedGeometry instanceof ArrayBuffer) {
  36833. var binaryInfo = mesh._binaryInfo;
  36834. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36835. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36836. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36837. }
  36838. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36839. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36840. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36841. }
  36842. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36843. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36844. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36845. }
  36846. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36847. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36848. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36849. }
  36850. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36851. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36852. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36853. }
  36854. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36855. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36856. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36857. }
  36858. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36859. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36860. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36861. }
  36862. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36863. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36864. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36865. }
  36866. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36867. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36868. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36869. }
  36870. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36871. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36872. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36873. }
  36874. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36875. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36876. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36877. }
  36878. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36879. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36880. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36881. }
  36882. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36883. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36884. mesh.setIndices(indicesData, null);
  36885. }
  36886. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36887. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36888. mesh.subMeshes = [];
  36889. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36890. var materialIndex = subMeshesData[(i * 5) + 0];
  36891. var verticesStart = subMeshesData[(i * 5) + 1];
  36892. var verticesCount = subMeshesData[(i * 5) + 2];
  36893. var indexStart = subMeshesData[(i * 5) + 3];
  36894. var indexCount = subMeshesData[(i * 5) + 4];
  36895. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36896. }
  36897. }
  36898. }
  36899. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36900. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36901. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36902. if (parsedGeometry.tangents) {
  36903. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36904. }
  36905. if (parsedGeometry.uvs) {
  36906. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36907. }
  36908. if (parsedGeometry.uvs2) {
  36909. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36910. }
  36911. if (parsedGeometry.uvs3) {
  36912. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36913. }
  36914. if (parsedGeometry.uvs4) {
  36915. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36916. }
  36917. if (parsedGeometry.uvs5) {
  36918. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36919. }
  36920. if (parsedGeometry.uvs6) {
  36921. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36922. }
  36923. if (parsedGeometry.colors) {
  36924. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36925. }
  36926. if (parsedGeometry.matricesIndices) {
  36927. if (!parsedGeometry.matricesIndices._isExpanded) {
  36928. var floatIndices = [];
  36929. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36930. var matricesIndex = parsedGeometry.matricesIndices[i];
  36931. floatIndices.push(matricesIndex & 0x000000FF);
  36932. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36933. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36934. floatIndices.push(matricesIndex >> 24);
  36935. }
  36936. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36937. }
  36938. else {
  36939. delete parsedGeometry.matricesIndices._isExpanded;
  36940. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36941. }
  36942. }
  36943. if (parsedGeometry.matricesIndicesExtra) {
  36944. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36945. var floatIndices = [];
  36946. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36947. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36948. floatIndices.push(matricesIndex & 0x000000FF);
  36949. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36950. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36951. floatIndices.push(matricesIndex >> 24);
  36952. }
  36953. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36954. }
  36955. else {
  36956. delete parsedGeometry.matricesIndices._isExpanded;
  36957. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36958. }
  36959. }
  36960. if (parsedGeometry.matricesWeights) {
  36961. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36962. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36963. }
  36964. if (parsedGeometry.matricesWeightsExtra) {
  36965. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36966. }
  36967. mesh.setIndices(parsedGeometry.indices, null);
  36968. }
  36969. // SubMeshes
  36970. if (parsedGeometry.subMeshes) {
  36971. mesh.subMeshes = [];
  36972. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36973. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36974. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36975. }
  36976. }
  36977. // Flat shading
  36978. if (mesh._shouldGenerateFlatShading) {
  36979. mesh.convertToFlatShadedMesh();
  36980. delete mesh._shouldGenerateFlatShading;
  36981. }
  36982. // Update
  36983. mesh.computeWorldMatrix(true);
  36984. // Octree
  36985. var sceneOctree = scene.selectionOctree;
  36986. if (sceneOctree !== undefined && sceneOctree !== null) {
  36987. sceneOctree.addMesh(mesh);
  36988. }
  36989. };
  36990. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36991. var epsilon = 1e-3;
  36992. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36993. return;
  36994. }
  36995. var noInfluenceBoneIndex = 0.0;
  36996. if (parsedGeometry.skeletonId > -1) {
  36997. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36998. if (!skeleton) {
  36999. return;
  37000. }
  37001. noInfluenceBoneIndex = skeleton.bones.length;
  37002. }
  37003. else {
  37004. return;
  37005. }
  37006. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  37007. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37008. var matricesWeights = parsedGeometry.matricesWeights;
  37009. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  37010. var influencers = parsedGeometry.numBoneInfluencer;
  37011. var size = matricesWeights.length;
  37012. for (var i = 0; i < size; i += 4) {
  37013. var weight = 0.0;
  37014. var firstZeroWeight = -1;
  37015. for (var j = 0; j < 4; j++) {
  37016. var w = matricesWeights[i + j];
  37017. weight += w;
  37018. if (w < epsilon && firstZeroWeight < 0) {
  37019. firstZeroWeight = j;
  37020. }
  37021. }
  37022. if (matricesWeightsExtra) {
  37023. for (var j = 0; j < 4; j++) {
  37024. var w = matricesWeightsExtra[i + j];
  37025. weight += w;
  37026. if (w < epsilon && firstZeroWeight < 0) {
  37027. firstZeroWeight = j + 4;
  37028. }
  37029. }
  37030. }
  37031. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  37032. firstZeroWeight = influencers - 1;
  37033. }
  37034. if (weight > epsilon) {
  37035. var mweight = 1.0 / weight;
  37036. for (var j = 0; j < 4; j++) {
  37037. matricesWeights[i + j] *= mweight;
  37038. }
  37039. if (matricesWeightsExtra) {
  37040. for (var j = 0; j < 4; j++) {
  37041. matricesWeightsExtra[i + j] *= mweight;
  37042. }
  37043. }
  37044. }
  37045. else {
  37046. if (firstZeroWeight >= 4) {
  37047. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  37048. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  37049. }
  37050. else {
  37051. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  37052. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  37053. }
  37054. }
  37055. }
  37056. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  37057. if (parsedGeometry.matricesWeightsExtra) {
  37058. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  37059. }
  37060. };
  37061. /**
  37062. * Create a new geometry from persisted data (Using .babylon file format)
  37063. * @param parsedVertexData defines the persisted data
  37064. * @param scene defines the hosting scene
  37065. * @param rootUrl defines the root url to use to load assets (like delayed data)
  37066. * @returns the new geometry object
  37067. */
  37068. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  37069. if (scene.getGeometryByID(parsedVertexData.id)) {
  37070. return null; // null since geometry could be something else than a box...
  37071. }
  37072. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  37073. if (BABYLON.Tags) {
  37074. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  37075. }
  37076. if (parsedVertexData.delayLoadingFile) {
  37077. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37078. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  37079. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  37080. geometry._delayInfo = [];
  37081. if (parsedVertexData.hasUVs) {
  37082. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  37083. }
  37084. if (parsedVertexData.hasUVs2) {
  37085. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  37086. }
  37087. if (parsedVertexData.hasUVs3) {
  37088. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  37089. }
  37090. if (parsedVertexData.hasUVs4) {
  37091. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  37092. }
  37093. if (parsedVertexData.hasUVs5) {
  37094. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  37095. }
  37096. if (parsedVertexData.hasUVs6) {
  37097. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  37098. }
  37099. if (parsedVertexData.hasColors) {
  37100. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  37101. }
  37102. if (parsedVertexData.hasMatricesIndices) {
  37103. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37104. }
  37105. if (parsedVertexData.hasMatricesWeights) {
  37106. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37107. }
  37108. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  37109. }
  37110. else {
  37111. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  37112. }
  37113. scene.pushGeometry(geometry, true);
  37114. return geometry;
  37115. };
  37116. return Geometry;
  37117. }());
  37118. BABYLON.Geometry = Geometry;
  37119. // Primitives
  37120. /// Abstract class
  37121. /**
  37122. * Abstract class used to provide common services for all typed geometries
  37123. */
  37124. var _PrimitiveGeometry = /** @class */ (function (_super) {
  37125. __extends(_PrimitiveGeometry, _super);
  37126. /**
  37127. * Creates a new typed geometry
  37128. * @param id defines the unique ID of the geometry
  37129. * @param scene defines the hosting scene
  37130. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37131. * @param mesh defines the hosting mesh (can be null)
  37132. */
  37133. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  37134. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  37135. if (mesh === void 0) { mesh = null; }
  37136. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  37137. _this._canBeRegenerated = _canBeRegenerated;
  37138. _this._beingRegenerated = true;
  37139. _this.regenerate();
  37140. _this._beingRegenerated = false;
  37141. return _this;
  37142. }
  37143. /**
  37144. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  37145. * @returns true if the geometry can be regenerated
  37146. */
  37147. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  37148. return this._canBeRegenerated;
  37149. };
  37150. /**
  37151. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  37152. */
  37153. _PrimitiveGeometry.prototype.regenerate = function () {
  37154. if (!this._canBeRegenerated) {
  37155. return;
  37156. }
  37157. this._beingRegenerated = true;
  37158. this.setAllVerticesData(this._regenerateVertexData(), false);
  37159. this._beingRegenerated = false;
  37160. };
  37161. /**
  37162. * Clone the geometry
  37163. * @param id defines the unique ID of the new geometry
  37164. * @returns the new geometry
  37165. */
  37166. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  37167. return _super.prototype.copy.call(this, id);
  37168. };
  37169. // overrides
  37170. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37171. if (!this._beingRegenerated) {
  37172. return;
  37173. }
  37174. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  37175. };
  37176. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  37177. if (!this._beingRegenerated) {
  37178. return;
  37179. }
  37180. _super.prototype.setVerticesData.call(this, kind, data, false);
  37181. };
  37182. // to override
  37183. /** @ignore */
  37184. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  37185. throw new Error("Abstract method");
  37186. };
  37187. _PrimitiveGeometry.prototype.copy = function (id) {
  37188. throw new Error("Must be overriden in sub-classes.");
  37189. };
  37190. _PrimitiveGeometry.prototype.serialize = function () {
  37191. var serializationObject = _super.prototype.serialize.call(this);
  37192. serializationObject.canBeRegenerated = this.canBeRegenerated();
  37193. return serializationObject;
  37194. };
  37195. return _PrimitiveGeometry;
  37196. }(Geometry));
  37197. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  37198. /**
  37199. * Creates a ribbon geometry
  37200. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  37201. */
  37202. var RibbonGeometry = /** @class */ (function (_super) {
  37203. __extends(RibbonGeometry, _super);
  37204. /**
  37205. * Creates a ribbon geometry
  37206. * @param id defines the unique ID of the geometry
  37207. * @param scene defines the hosting scene
  37208. * @param pathArray defines the array of paths to use
  37209. * @param closeArray defines if the last path and the first path must be joined
  37210. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  37211. * @param offset defines the offset between points
  37212. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37213. * @param mesh defines the hosting mesh (can be null)
  37214. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37215. */
  37216. function RibbonGeometry(id, scene,
  37217. /**
  37218. * Defines the array of paths to use
  37219. */
  37220. pathArray,
  37221. /**
  37222. * Defines if the last and first points of each path in your pathArray must be joined
  37223. */
  37224. closeArray,
  37225. /**
  37226. * Defines if the last and first points of each path in your pathArray must be joined
  37227. */
  37228. closePath,
  37229. /**
  37230. * Defines the offset between points
  37231. */
  37232. offset, canBeRegenerated, mesh,
  37233. /**
  37234. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37235. */
  37236. side) {
  37237. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37238. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37239. _this.pathArray = pathArray;
  37240. _this.closeArray = closeArray;
  37241. _this.closePath = closePath;
  37242. _this.offset = offset;
  37243. _this.side = side;
  37244. return _this;
  37245. }
  37246. /** @ignore */
  37247. RibbonGeometry.prototype._regenerateVertexData = function () {
  37248. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  37249. };
  37250. RibbonGeometry.prototype.copy = function (id) {
  37251. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  37252. };
  37253. return RibbonGeometry;
  37254. }(_PrimitiveGeometry));
  37255. BABYLON.RibbonGeometry = RibbonGeometry;
  37256. /**
  37257. * Creates a box geometry
  37258. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  37259. */
  37260. var BoxGeometry = /** @class */ (function (_super) {
  37261. __extends(BoxGeometry, _super);
  37262. /**
  37263. * Creates a box geometry
  37264. * @param id defines the unique ID of the geometry
  37265. * @param scene defines the hosting scene
  37266. * @param size defines the zise of the box (width, height and depth are the same)
  37267. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37268. * @param mesh defines the hosting mesh (can be null)
  37269. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37270. */
  37271. function BoxGeometry(id, scene,
  37272. /**
  37273. * Defines the zise of the box (width, height and depth are the same)
  37274. */
  37275. size, canBeRegenerated, mesh,
  37276. /**
  37277. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37278. */
  37279. side) {
  37280. if (mesh === void 0) { mesh = null; }
  37281. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37282. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37283. _this.size = size;
  37284. _this.side = side;
  37285. return _this;
  37286. }
  37287. BoxGeometry.prototype._regenerateVertexData = function () {
  37288. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  37289. };
  37290. BoxGeometry.prototype.copy = function (id) {
  37291. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  37292. };
  37293. BoxGeometry.prototype.serialize = function () {
  37294. var serializationObject = _super.prototype.serialize.call(this);
  37295. serializationObject.size = this.size;
  37296. return serializationObject;
  37297. };
  37298. BoxGeometry.Parse = function (parsedBox, scene) {
  37299. if (scene.getGeometryByID(parsedBox.id)) {
  37300. return null; // null since geometry could be something else than a box...
  37301. }
  37302. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  37303. if (BABYLON.Tags) {
  37304. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  37305. }
  37306. scene.pushGeometry(box, true);
  37307. return box;
  37308. };
  37309. return BoxGeometry;
  37310. }(_PrimitiveGeometry));
  37311. BABYLON.BoxGeometry = BoxGeometry;
  37312. /**
  37313. * Creates a sphere geometry
  37314. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  37315. */
  37316. var SphereGeometry = /** @class */ (function (_super) {
  37317. __extends(SphereGeometry, _super);
  37318. /**
  37319. * Create a new sphere geometry
  37320. * @param id defines the unique ID of the geometry
  37321. * @param scene defines the hosting scene
  37322. * @param segments defines the number of segments to use to create the sphere
  37323. * @param diameter defines the diameter of the sphere
  37324. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37325. * @param mesh defines the hosting mesh (can be null)
  37326. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37327. */
  37328. function SphereGeometry(id, scene,
  37329. /**
  37330. * Defines the number of segments to use to create the sphere
  37331. */
  37332. segments,
  37333. /**
  37334. * Defines the diameter of the sphere
  37335. */
  37336. diameter, canBeRegenerated, mesh,
  37337. /**
  37338. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37339. */
  37340. side) {
  37341. if (mesh === void 0) { mesh = null; }
  37342. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37343. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37344. _this.segments = segments;
  37345. _this.diameter = diameter;
  37346. _this.side = side;
  37347. return _this;
  37348. }
  37349. SphereGeometry.prototype._regenerateVertexData = function () {
  37350. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  37351. };
  37352. SphereGeometry.prototype.copy = function (id) {
  37353. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  37354. };
  37355. SphereGeometry.prototype.serialize = function () {
  37356. var serializationObject = _super.prototype.serialize.call(this);
  37357. serializationObject.segments = this.segments;
  37358. serializationObject.diameter = this.diameter;
  37359. return serializationObject;
  37360. };
  37361. SphereGeometry.Parse = function (parsedSphere, scene) {
  37362. if (scene.getGeometryByID(parsedSphere.id)) {
  37363. return null; // null since geometry could be something else than a sphere...
  37364. }
  37365. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37366. if (BABYLON.Tags) {
  37367. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37368. }
  37369. scene.pushGeometry(sphere, true);
  37370. return sphere;
  37371. };
  37372. return SphereGeometry;
  37373. }(_PrimitiveGeometry));
  37374. BABYLON.SphereGeometry = SphereGeometry;
  37375. /**
  37376. * Creates a disc geometry
  37377. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  37378. */
  37379. var DiscGeometry = /** @class */ (function (_super) {
  37380. __extends(DiscGeometry, _super);
  37381. /**
  37382. * Creates a new disc geometry
  37383. * @param id defines the unique ID of the geometry
  37384. * @param scene defines the hosting scene
  37385. * @param radius defines the radius of the disc
  37386. * @param tessellation defines the tesselation factor to apply to the disc
  37387. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37388. * @param mesh defines the hosting mesh (can be null)
  37389. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37390. */
  37391. function DiscGeometry(id, scene,
  37392. /**
  37393. * Defines the radius of the disc
  37394. */
  37395. radius,
  37396. /**
  37397. * Defines the tesselation factor to apply to the disc
  37398. */
  37399. tessellation, canBeRegenerated, mesh,
  37400. /**
  37401. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37402. */
  37403. side) {
  37404. if (mesh === void 0) { mesh = null; }
  37405. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37406. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37407. _this.radius = radius;
  37408. _this.tessellation = tessellation;
  37409. _this.side = side;
  37410. return _this;
  37411. }
  37412. DiscGeometry.prototype._regenerateVertexData = function () {
  37413. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37414. };
  37415. DiscGeometry.prototype.copy = function (id) {
  37416. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37417. };
  37418. return DiscGeometry;
  37419. }(_PrimitiveGeometry));
  37420. BABYLON.DiscGeometry = DiscGeometry;
  37421. /**
  37422. * Creates a new cylinder geometry
  37423. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  37424. */
  37425. var CylinderGeometry = /** @class */ (function (_super) {
  37426. __extends(CylinderGeometry, _super);
  37427. /**
  37428. * Creates a new cylinder geometry
  37429. * @param id defines the unique ID of the geometry
  37430. * @param scene defines the hosting scene
  37431. * @param height defines the height of the cylinder
  37432. * @param diameterTop defines the diameter of the cylinder's top cap
  37433. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  37434. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  37435. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  37436. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37437. * @param mesh defines the hosting mesh (can be null)
  37438. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37439. */
  37440. function CylinderGeometry(id, scene,
  37441. /**
  37442. * Defines the height of the cylinder
  37443. */
  37444. height,
  37445. /**
  37446. * Defines the diameter of the cylinder's top cap
  37447. */
  37448. diameterTop,
  37449. /**
  37450. * Defines the diameter of the cylinder's bottom cap
  37451. */
  37452. diameterBottom,
  37453. /**
  37454. * Defines the tessellation factor to apply to the cylinder
  37455. */
  37456. tessellation,
  37457. /**
  37458. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  37459. */
  37460. subdivisions, canBeRegenerated, mesh,
  37461. /**
  37462. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37463. */
  37464. side) {
  37465. if (subdivisions === void 0) { subdivisions = 1; }
  37466. if (mesh === void 0) { mesh = null; }
  37467. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37468. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37469. _this.height = height;
  37470. _this.diameterTop = diameterTop;
  37471. _this.diameterBottom = diameterBottom;
  37472. _this.tessellation = tessellation;
  37473. _this.subdivisions = subdivisions;
  37474. _this.side = side;
  37475. return _this;
  37476. }
  37477. CylinderGeometry.prototype._regenerateVertexData = function () {
  37478. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37479. };
  37480. CylinderGeometry.prototype.copy = function (id) {
  37481. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37482. };
  37483. CylinderGeometry.prototype.serialize = function () {
  37484. var serializationObject = _super.prototype.serialize.call(this);
  37485. serializationObject.height = this.height;
  37486. serializationObject.diameterTop = this.diameterTop;
  37487. serializationObject.diameterBottom = this.diameterBottom;
  37488. serializationObject.tessellation = this.tessellation;
  37489. return serializationObject;
  37490. };
  37491. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  37492. if (scene.getGeometryByID(parsedCylinder.id)) {
  37493. return null; // null since geometry could be something else than a cylinder...
  37494. }
  37495. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37496. if (BABYLON.Tags) {
  37497. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37498. }
  37499. scene.pushGeometry(cylinder, true);
  37500. return cylinder;
  37501. };
  37502. return CylinderGeometry;
  37503. }(_PrimitiveGeometry));
  37504. BABYLON.CylinderGeometry = CylinderGeometry;
  37505. /**
  37506. * Creates a new torus geometry
  37507. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  37508. */
  37509. var TorusGeometry = /** @class */ (function (_super) {
  37510. __extends(TorusGeometry, _super);
  37511. /**
  37512. * Creates a new torus geometry
  37513. * @param id defines the unique ID of the geometry
  37514. * @param scene defines the hosting scene
  37515. * @param diameter defines the diameter of the torus
  37516. * @param thickness defines the thickness of the torus (ie. internal diameter)
  37517. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  37518. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37519. * @param mesh defines the hosting mesh (can be null)
  37520. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37521. */
  37522. function TorusGeometry(id, scene,
  37523. /**
  37524. * Defines the diameter of the torus
  37525. */
  37526. diameter,
  37527. /**
  37528. * Defines the thickness of the torus (ie. internal diameter)
  37529. */
  37530. thickness,
  37531. /**
  37532. * Defines the tesselation factor to apply to the torus
  37533. */
  37534. tessellation, canBeRegenerated, mesh,
  37535. /**
  37536. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37537. */
  37538. side) {
  37539. if (mesh === void 0) { mesh = null; }
  37540. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37541. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37542. _this.diameter = diameter;
  37543. _this.thickness = thickness;
  37544. _this.tessellation = tessellation;
  37545. _this.side = side;
  37546. return _this;
  37547. }
  37548. TorusGeometry.prototype._regenerateVertexData = function () {
  37549. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37550. };
  37551. TorusGeometry.prototype.copy = function (id) {
  37552. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37553. };
  37554. TorusGeometry.prototype.serialize = function () {
  37555. var serializationObject = _super.prototype.serialize.call(this);
  37556. serializationObject.diameter = this.diameter;
  37557. serializationObject.thickness = this.thickness;
  37558. serializationObject.tessellation = this.tessellation;
  37559. return serializationObject;
  37560. };
  37561. TorusGeometry.Parse = function (parsedTorus, scene) {
  37562. if (scene.getGeometryByID(parsedTorus.id)) {
  37563. return null; // null since geometry could be something else than a torus...
  37564. }
  37565. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37566. if (BABYLON.Tags) {
  37567. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37568. }
  37569. scene.pushGeometry(torus, true);
  37570. return torus;
  37571. };
  37572. return TorusGeometry;
  37573. }(_PrimitiveGeometry));
  37574. BABYLON.TorusGeometry = TorusGeometry;
  37575. /**
  37576. * Creates a new ground geometry
  37577. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  37578. */
  37579. var GroundGeometry = /** @class */ (function (_super) {
  37580. __extends(GroundGeometry, _super);
  37581. /**
  37582. * Creates a new ground geometry
  37583. * @param id defines the unique ID of the geometry
  37584. * @param scene defines the hosting scene
  37585. * @param width defines the width of the ground
  37586. * @param height defines the height of the ground
  37587. * @param subdivisions defines the subdivisions to apply to the ground
  37588. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37589. * @param mesh defines the hosting mesh (can be null)
  37590. */
  37591. function GroundGeometry(id, scene,
  37592. /**
  37593. * Defines the width of the ground
  37594. */
  37595. width,
  37596. /**
  37597. * Defines the height of the ground
  37598. */
  37599. height,
  37600. /**
  37601. * Defines the subdivisions to apply to the ground
  37602. */
  37603. subdivisions, canBeRegenerated, mesh) {
  37604. if (mesh === void 0) { mesh = null; }
  37605. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37606. _this.width = width;
  37607. _this.height = height;
  37608. _this.subdivisions = subdivisions;
  37609. return _this;
  37610. }
  37611. GroundGeometry.prototype._regenerateVertexData = function () {
  37612. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37613. };
  37614. GroundGeometry.prototype.copy = function (id) {
  37615. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37616. };
  37617. GroundGeometry.prototype.serialize = function () {
  37618. var serializationObject = _super.prototype.serialize.call(this);
  37619. serializationObject.width = this.width;
  37620. serializationObject.height = this.height;
  37621. serializationObject.subdivisions = this.subdivisions;
  37622. return serializationObject;
  37623. };
  37624. GroundGeometry.Parse = function (parsedGround, scene) {
  37625. if (scene.getGeometryByID(parsedGround.id)) {
  37626. return null; // null since geometry could be something else than a ground...
  37627. }
  37628. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37629. if (BABYLON.Tags) {
  37630. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37631. }
  37632. scene.pushGeometry(ground, true);
  37633. return ground;
  37634. };
  37635. return GroundGeometry;
  37636. }(_PrimitiveGeometry));
  37637. BABYLON.GroundGeometry = GroundGeometry;
  37638. /**
  37639. * Creates a tiled ground geometry
  37640. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  37641. */
  37642. var TiledGroundGeometry = /** @class */ (function (_super) {
  37643. __extends(TiledGroundGeometry, _super);
  37644. /**
  37645. * Creates a tiled ground geometry
  37646. * @param id defines the unique ID of the geometry
  37647. * @param scene defines the hosting scene
  37648. * @param xmin defines the minimum value on X axis
  37649. * @param zmin defines the minimum value on Z axis
  37650. * @param xmax defines the maximum value on X axis
  37651. * @param zmax defines the maximum value on Z axis
  37652. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  37653. * @param precision defines the precision to use when computing the tiles
  37654. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37655. * @param mesh defines the hosting mesh (can be null)
  37656. */
  37657. function TiledGroundGeometry(id, scene,
  37658. /**
  37659. * Defines the minimum value on X axis
  37660. */
  37661. xmin,
  37662. /**
  37663. * Defines the minimum value on Z axis
  37664. */
  37665. zmin,
  37666. /**
  37667. * Defines the maximum value on X axis
  37668. */
  37669. xmax,
  37670. /**
  37671. * Defines the maximum value on Z axis
  37672. */
  37673. zmax,
  37674. /**
  37675. * Defines the subdivisions to apply to the ground
  37676. */
  37677. subdivisions,
  37678. /**
  37679. * Defines the precision to use when computing the tiles
  37680. */
  37681. precision, canBeRegenerated, mesh) {
  37682. if (mesh === void 0) { mesh = null; }
  37683. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37684. _this.xmin = xmin;
  37685. _this.zmin = zmin;
  37686. _this.xmax = xmax;
  37687. _this.zmax = zmax;
  37688. _this.subdivisions = subdivisions;
  37689. _this.precision = precision;
  37690. return _this;
  37691. }
  37692. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  37693. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37694. };
  37695. TiledGroundGeometry.prototype.copy = function (id) {
  37696. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37697. };
  37698. return TiledGroundGeometry;
  37699. }(_PrimitiveGeometry));
  37700. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  37701. /**
  37702. * Creates a plane geometry
  37703. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  37704. */
  37705. var PlaneGeometry = /** @class */ (function (_super) {
  37706. __extends(PlaneGeometry, _super);
  37707. /**
  37708. * Creates a plane geometry
  37709. * @param id defines the unique ID of the geometry
  37710. * @param scene defines the hosting scene
  37711. * @param size defines the size of the plane (width === height)
  37712. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37713. * @param mesh defines the hosting mesh (can be null)
  37714. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37715. */
  37716. function PlaneGeometry(id, scene,
  37717. /**
  37718. * Defines the size of the plane (width === height)
  37719. */
  37720. size, canBeRegenerated, mesh,
  37721. /**
  37722. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37723. */
  37724. side) {
  37725. if (mesh === void 0) { mesh = null; }
  37726. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37727. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37728. _this.size = size;
  37729. _this.side = side;
  37730. return _this;
  37731. }
  37732. PlaneGeometry.prototype._regenerateVertexData = function () {
  37733. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37734. };
  37735. PlaneGeometry.prototype.copy = function (id) {
  37736. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37737. };
  37738. PlaneGeometry.prototype.serialize = function () {
  37739. var serializationObject = _super.prototype.serialize.call(this);
  37740. serializationObject.size = this.size;
  37741. return serializationObject;
  37742. };
  37743. PlaneGeometry.Parse = function (parsedPlane, scene) {
  37744. if (scene.getGeometryByID(parsedPlane.id)) {
  37745. return null; // null since geometry could be something else than a ground...
  37746. }
  37747. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37748. if (BABYLON.Tags) {
  37749. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37750. }
  37751. scene.pushGeometry(plane, true);
  37752. return plane;
  37753. };
  37754. return PlaneGeometry;
  37755. }(_PrimitiveGeometry));
  37756. BABYLON.PlaneGeometry = PlaneGeometry;
  37757. /**
  37758. * Creates a torus knot geometry
  37759. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  37760. */
  37761. var TorusKnotGeometry = /** @class */ (function (_super) {
  37762. __extends(TorusKnotGeometry, _super);
  37763. /**
  37764. * Creates a torus knot geometry
  37765. * @param id defines the unique ID of the geometry
  37766. * @param scene defines the hosting scene
  37767. * @param radius defines the radius of the torus knot
  37768. * @param tube defines the thickness of the torus knot tube
  37769. * @param radialSegments defines the number of radial segments
  37770. * @param tubularSegments defines the number of tubular segments
  37771. * @param p defines the first number of windings
  37772. * @param q defines the second number of windings
  37773. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  37774. * @param mesh defines the hosting mesh (can be null)
  37775. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37776. */
  37777. function TorusKnotGeometry(id, scene,
  37778. /**
  37779. * Defines the radius of the torus knot
  37780. */
  37781. radius,
  37782. /**
  37783. * Defines the thickness of the torus knot tube
  37784. */
  37785. tube,
  37786. /**
  37787. * Defines the number of radial segments
  37788. */
  37789. radialSegments,
  37790. /**
  37791. * Defines the number of tubular segments
  37792. */
  37793. tubularSegments,
  37794. /**
  37795. * Defines the first number of windings
  37796. */
  37797. p,
  37798. /**
  37799. * Defines the second number of windings
  37800. */
  37801. q, canBeRegenerated, mesh,
  37802. /**
  37803. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37804. */
  37805. side) {
  37806. if (mesh === void 0) { mesh = null; }
  37807. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37808. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37809. _this.radius = radius;
  37810. _this.tube = tube;
  37811. _this.radialSegments = radialSegments;
  37812. _this.tubularSegments = tubularSegments;
  37813. _this.p = p;
  37814. _this.q = q;
  37815. _this.side = side;
  37816. return _this;
  37817. }
  37818. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37819. 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 });
  37820. };
  37821. TorusKnotGeometry.prototype.copy = function (id) {
  37822. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37823. };
  37824. TorusKnotGeometry.prototype.serialize = function () {
  37825. var serializationObject = _super.prototype.serialize.call(this);
  37826. serializationObject.radius = this.radius;
  37827. serializationObject.tube = this.tube;
  37828. serializationObject.radialSegments = this.radialSegments;
  37829. serializationObject.tubularSegments = this.tubularSegments;
  37830. serializationObject.p = this.p;
  37831. serializationObject.q = this.q;
  37832. return serializationObject;
  37833. };
  37834. ;
  37835. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37836. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37837. return null; // null since geometry could be something else than a ground...
  37838. }
  37839. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37840. if (BABYLON.Tags) {
  37841. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37842. }
  37843. scene.pushGeometry(torusKnot, true);
  37844. return torusKnot;
  37845. };
  37846. return TorusKnotGeometry;
  37847. }(_PrimitiveGeometry));
  37848. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37849. //}
  37850. })(BABYLON || (BABYLON = {}));
  37851. //# sourceMappingURL=babylon.geometry.js.map
  37852. "use strict";
  37853. var BABYLON;
  37854. (function (BABYLON) {
  37855. /**
  37856. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37857. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37858. */
  37859. var PostProcessManager = /** @class */ (function () {
  37860. /**
  37861. * Creates a new instance PostProcess
  37862. * @param scene The scene that the post process is associated with.
  37863. */
  37864. function PostProcessManager(scene) {
  37865. this._vertexBuffers = {};
  37866. this._scene = scene;
  37867. }
  37868. PostProcessManager.prototype._prepareBuffers = function () {
  37869. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37870. return;
  37871. }
  37872. // VBO
  37873. var vertices = [];
  37874. vertices.push(1, 1);
  37875. vertices.push(-1, 1);
  37876. vertices.push(-1, -1);
  37877. vertices.push(1, -1);
  37878. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37879. this._buildIndexBuffer();
  37880. };
  37881. PostProcessManager.prototype._buildIndexBuffer = function () {
  37882. // Indices
  37883. var indices = [];
  37884. indices.push(0);
  37885. indices.push(1);
  37886. indices.push(2);
  37887. indices.push(0);
  37888. indices.push(2);
  37889. indices.push(3);
  37890. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37891. };
  37892. /**
  37893. * Rebuilds the vertex buffers of the manager.
  37894. */
  37895. PostProcessManager.prototype._rebuild = function () {
  37896. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37897. if (!vb) {
  37898. return;
  37899. }
  37900. vb._rebuild();
  37901. this._buildIndexBuffer();
  37902. };
  37903. // Methods
  37904. /**
  37905. * Prepares a frame to be run through a post process.
  37906. * @param sourceTexture The input texture to the post procesess. (default: null)
  37907. * @param postProcesses An array of post processes to be run. (default: null)
  37908. * @returns True if the post processes were able to be run.
  37909. */
  37910. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37911. if (sourceTexture === void 0) { sourceTexture = null; }
  37912. if (postProcesses === void 0) { postProcesses = null; }
  37913. var camera = this._scene.activeCamera;
  37914. if (!camera) {
  37915. return false;
  37916. }
  37917. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37918. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37919. return false;
  37920. }
  37921. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37922. return true;
  37923. };
  37924. /**
  37925. * Manually render a set of post processes to a texture.
  37926. * @param postProcesses An array of post processes to be run.
  37927. * @param targetTexture The target texture to render to.
  37928. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37929. */
  37930. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37931. if (targetTexture === void 0) { targetTexture = null; }
  37932. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37933. var engine = this._scene.getEngine();
  37934. for (var index = 0; index < postProcesses.length; index++) {
  37935. if (index < postProcesses.length - 1) {
  37936. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37937. }
  37938. else {
  37939. if (targetTexture) {
  37940. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37941. }
  37942. else {
  37943. engine.restoreDefaultFramebuffer();
  37944. }
  37945. }
  37946. var pp = postProcesses[index];
  37947. var effect = pp.apply();
  37948. if (effect) {
  37949. pp.onBeforeRenderObservable.notifyObservers(effect);
  37950. // VBOs
  37951. this._prepareBuffers();
  37952. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37953. // Draw order
  37954. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37955. pp.onAfterRenderObservable.notifyObservers(effect);
  37956. }
  37957. }
  37958. // Restore depth buffer
  37959. engine.setDepthBuffer(true);
  37960. engine.setDepthWrite(true);
  37961. };
  37962. /**
  37963. * Finalize the result of the output of the postprocesses.
  37964. * @param doNotPresent If true the result will not be displayed to the screen.
  37965. * @param targetTexture The target texture to render to.
  37966. * @param faceIndex The index of the face to bind the target texture to.
  37967. * @param postProcesses The array of post processes to render.
  37968. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37969. */
  37970. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37971. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37972. var camera = this._scene.activeCamera;
  37973. if (!camera) {
  37974. return;
  37975. }
  37976. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37977. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37978. return;
  37979. }
  37980. var engine = this._scene.getEngine();
  37981. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37982. var pp = postProcesses[index];
  37983. if (index < len - 1) {
  37984. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37985. }
  37986. else {
  37987. if (targetTexture) {
  37988. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37989. }
  37990. else {
  37991. engine.restoreDefaultFramebuffer();
  37992. }
  37993. }
  37994. if (doNotPresent) {
  37995. break;
  37996. }
  37997. var effect = pp.apply();
  37998. if (effect) {
  37999. pp.onBeforeRenderObservable.notifyObservers(effect);
  38000. // VBOs
  38001. this._prepareBuffers();
  38002. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  38003. // Draw order
  38004. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  38005. pp.onAfterRenderObservable.notifyObservers(effect);
  38006. }
  38007. }
  38008. // Restore states
  38009. engine.setDepthBuffer(true);
  38010. engine.setDepthWrite(true);
  38011. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38012. };
  38013. /**
  38014. * Disposes of the post process manager.
  38015. */
  38016. PostProcessManager.prototype.dispose = function () {
  38017. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38018. if (buffer) {
  38019. buffer.dispose();
  38020. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38021. }
  38022. if (this._indexBuffer) {
  38023. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38024. this._indexBuffer = null;
  38025. }
  38026. };
  38027. return PostProcessManager;
  38028. }());
  38029. BABYLON.PostProcessManager = PostProcessManager;
  38030. })(BABYLON || (BABYLON = {}));
  38031. //# sourceMappingURL=babylon.postProcessManager.js.map
  38032. "use strict";
  38033. var BABYLON;
  38034. (function (BABYLON) {
  38035. /**
  38036. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  38037. */
  38038. var PerformanceMonitor = /** @class */ (function () {
  38039. /**
  38040. * constructor
  38041. * @param frameSampleSize The number of samples required to saturate the sliding window
  38042. */
  38043. function PerformanceMonitor(frameSampleSize) {
  38044. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  38045. this._enabled = true;
  38046. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  38047. }
  38048. /**
  38049. * Samples current frame
  38050. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  38051. */
  38052. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  38053. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  38054. if (!this._enabled)
  38055. return;
  38056. if (this._lastFrameTimeMs != null) {
  38057. var dt = timeMs - this._lastFrameTimeMs;
  38058. this._rollingFrameTime.add(dt);
  38059. }
  38060. this._lastFrameTimeMs = timeMs;
  38061. };
  38062. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  38063. /**
  38064. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  38065. * @return Average frame time in milliseconds
  38066. */
  38067. get: function () {
  38068. return this._rollingFrameTime.average;
  38069. },
  38070. enumerable: true,
  38071. configurable: true
  38072. });
  38073. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  38074. /**
  38075. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  38076. * @return Frame time variance in milliseconds squared
  38077. */
  38078. get: function () {
  38079. return this._rollingFrameTime.variance;
  38080. },
  38081. enumerable: true,
  38082. configurable: true
  38083. });
  38084. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  38085. /**
  38086. * Returns the frame time of the most recent frame
  38087. * @return Frame time in milliseconds
  38088. */
  38089. get: function () {
  38090. return this._rollingFrameTime.history(0);
  38091. },
  38092. enumerable: true,
  38093. configurable: true
  38094. });
  38095. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  38096. /**
  38097. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  38098. * @return Framerate in frames per second
  38099. */
  38100. get: function () {
  38101. return 1000.0 / this._rollingFrameTime.average;
  38102. },
  38103. enumerable: true,
  38104. configurable: true
  38105. });
  38106. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  38107. /**
  38108. * Returns the average framerate in frames per second using the most recent frame time
  38109. * @return Framerate in frames per second
  38110. */
  38111. get: function () {
  38112. var history = this._rollingFrameTime.history(0);
  38113. if (history === 0) {
  38114. return 0;
  38115. }
  38116. return 1000.0 / history;
  38117. },
  38118. enumerable: true,
  38119. configurable: true
  38120. });
  38121. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  38122. /**
  38123. * Returns true if enough samples have been taken to completely fill the sliding window
  38124. * @return true if saturated
  38125. */
  38126. get: function () {
  38127. return this._rollingFrameTime.isSaturated();
  38128. },
  38129. enumerable: true,
  38130. configurable: true
  38131. });
  38132. /**
  38133. * Enables contributions to the sliding window sample set
  38134. */
  38135. PerformanceMonitor.prototype.enable = function () {
  38136. this._enabled = true;
  38137. };
  38138. /**
  38139. * Disables contributions to the sliding window sample set
  38140. * Samples will not be interpolated over the disabled period
  38141. */
  38142. PerformanceMonitor.prototype.disable = function () {
  38143. this._enabled = false;
  38144. //clear last sample to avoid interpolating over the disabled period when next enabled
  38145. this._lastFrameTimeMs = null;
  38146. };
  38147. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  38148. /**
  38149. * Returns true if sampling is enabled
  38150. * @return true if enabled
  38151. */
  38152. get: function () {
  38153. return this._enabled;
  38154. },
  38155. enumerable: true,
  38156. configurable: true
  38157. });
  38158. /**
  38159. * Resets performance monitor
  38160. */
  38161. PerformanceMonitor.prototype.reset = function () {
  38162. //clear last sample to avoid interpolating over the disabled period when next enabled
  38163. this._lastFrameTimeMs = null;
  38164. //wipe record
  38165. this._rollingFrameTime.reset();
  38166. };
  38167. return PerformanceMonitor;
  38168. }());
  38169. BABYLON.PerformanceMonitor = PerformanceMonitor;
  38170. /**
  38171. * RollingAverage
  38172. *
  38173. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  38174. */
  38175. var RollingAverage = /** @class */ (function () {
  38176. /**
  38177. * constructor
  38178. * @param length The number of samples required to saturate the sliding window
  38179. */
  38180. function RollingAverage(length) {
  38181. this._samples = new Array(length);
  38182. this.reset();
  38183. }
  38184. /**
  38185. * Adds a sample to the sample set
  38186. * @param v The sample value
  38187. */
  38188. RollingAverage.prototype.add = function (v) {
  38189. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  38190. var delta;
  38191. //we need to check if we've already wrapped round
  38192. if (this.isSaturated()) {
  38193. //remove bottom of stack from mean
  38194. var bottomValue = this._samples[this._pos];
  38195. delta = bottomValue - this.average;
  38196. this.average -= delta / (this._sampleCount - 1);
  38197. this._m2 -= delta * (bottomValue - this.average);
  38198. }
  38199. else {
  38200. this._sampleCount++;
  38201. }
  38202. //add new value to mean
  38203. delta = v - this.average;
  38204. this.average += delta / (this._sampleCount);
  38205. this._m2 += delta * (v - this.average);
  38206. //set the new variance
  38207. this.variance = this._m2 / (this._sampleCount - 1);
  38208. this._samples[this._pos] = v;
  38209. this._pos++;
  38210. this._pos %= this._samples.length; //positive wrap around
  38211. };
  38212. /**
  38213. * Returns previously added values or null if outside of history or outside the sliding window domain
  38214. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  38215. * @return Value previously recorded with add() or null if outside of range
  38216. */
  38217. RollingAverage.prototype.history = function (i) {
  38218. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  38219. return 0;
  38220. }
  38221. var i0 = this._wrapPosition(this._pos - 1.0);
  38222. return this._samples[this._wrapPosition(i0 - i)];
  38223. };
  38224. /**
  38225. * Returns true if enough samples have been taken to completely fill the sliding window
  38226. * @return true if sample-set saturated
  38227. */
  38228. RollingAverage.prototype.isSaturated = function () {
  38229. return this._sampleCount >= this._samples.length;
  38230. };
  38231. /**
  38232. * Resets the rolling average (equivalent to 0 samples taken so far)
  38233. */
  38234. RollingAverage.prototype.reset = function () {
  38235. this.average = 0;
  38236. this.variance = 0;
  38237. this._sampleCount = 0;
  38238. this._pos = 0;
  38239. this._m2 = 0;
  38240. };
  38241. /**
  38242. * Wraps a value around the sample range boundaries
  38243. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  38244. * @return Wrapped position in sample range
  38245. */
  38246. RollingAverage.prototype._wrapPosition = function (i) {
  38247. var max = this._samples.length;
  38248. return ((i % max) + max) % max;
  38249. };
  38250. return RollingAverage;
  38251. }());
  38252. BABYLON.RollingAverage = RollingAverage;
  38253. })(BABYLON || (BABYLON = {}));
  38254. //# sourceMappingURL=babylon.performanceMonitor.js.map
  38255. "use strict";
  38256. var BABYLON;
  38257. (function (BABYLON) {
  38258. /**
  38259. * This groups together the common properties used for image processing either in direct forward pass
  38260. * or through post processing effect depending on the use of the image processing pipeline in your scene
  38261. * or not.
  38262. */
  38263. var ImageProcessingConfiguration = /** @class */ (function () {
  38264. function ImageProcessingConfiguration() {
  38265. /**
  38266. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  38267. */
  38268. this.colorCurves = new BABYLON.ColorCurves();
  38269. this._colorCurvesEnabled = false;
  38270. this._colorGradingEnabled = false;
  38271. this._colorGradingWithGreenDepth = true;
  38272. this._colorGradingBGR = true;
  38273. this._exposure = 1.0;
  38274. this._toneMappingEnabled = false;
  38275. this._contrast = 1.0;
  38276. /**
  38277. * Vignette stretch size.
  38278. */
  38279. this.vignetteStretch = 0;
  38280. /**
  38281. * Vignette centre X Offset.
  38282. */
  38283. this.vignetteCentreX = 0;
  38284. /**
  38285. * Vignette centre Y Offset.
  38286. */
  38287. this.vignetteCentreY = 0;
  38288. /**
  38289. * Vignette weight or intensity of the vignette effect.
  38290. */
  38291. this.vignetteWeight = 1.5;
  38292. /**
  38293. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38294. * if vignetteEnabled is set to true.
  38295. */
  38296. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  38297. /**
  38298. * Camera field of view used by the Vignette effect.
  38299. */
  38300. this.vignetteCameraFov = 0.5;
  38301. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  38302. this._vignetteEnabled = false;
  38303. this._applyByPostProcess = false;
  38304. this._isEnabled = true;
  38305. /**
  38306. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  38307. */
  38308. this.onUpdateParameters = new BABYLON.Observable();
  38309. }
  38310. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  38311. /**
  38312. * Gets wether the color curves effect is enabled.
  38313. */
  38314. get: function () {
  38315. return this._colorCurvesEnabled;
  38316. },
  38317. /**
  38318. * Sets wether the color curves effect is enabled.
  38319. */
  38320. set: function (value) {
  38321. if (this._colorCurvesEnabled === value) {
  38322. return;
  38323. }
  38324. this._colorCurvesEnabled = value;
  38325. this._updateParameters();
  38326. },
  38327. enumerable: true,
  38328. configurable: true
  38329. });
  38330. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  38331. /**
  38332. * Gets wether the color grading effect is enabled.
  38333. */
  38334. get: function () {
  38335. return this._colorGradingEnabled;
  38336. },
  38337. /**
  38338. * Sets wether the color grading effect is enabled.
  38339. */
  38340. set: function (value) {
  38341. if (this._colorGradingEnabled === value) {
  38342. return;
  38343. }
  38344. this._colorGradingEnabled = value;
  38345. this._updateParameters();
  38346. },
  38347. enumerable: true,
  38348. configurable: true
  38349. });
  38350. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  38351. /**
  38352. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  38353. */
  38354. get: function () {
  38355. return this._colorGradingWithGreenDepth;
  38356. },
  38357. /**
  38358. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  38359. */
  38360. set: function (value) {
  38361. if (this._colorGradingWithGreenDepth === value) {
  38362. return;
  38363. }
  38364. this._colorGradingWithGreenDepth = value;
  38365. this._updateParameters();
  38366. },
  38367. enumerable: true,
  38368. configurable: true
  38369. });
  38370. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  38371. /**
  38372. * Gets wether the color grading texture contains BGR values.
  38373. */
  38374. get: function () {
  38375. return this._colorGradingBGR;
  38376. },
  38377. /**
  38378. * Sets wether the color grading texture contains BGR values.
  38379. */
  38380. set: function (value) {
  38381. if (this._colorGradingBGR === value) {
  38382. return;
  38383. }
  38384. this._colorGradingBGR = value;
  38385. this._updateParameters();
  38386. },
  38387. enumerable: true,
  38388. configurable: true
  38389. });
  38390. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  38391. /**
  38392. * Gets the Exposure used in the effect.
  38393. */
  38394. get: function () {
  38395. return this._exposure;
  38396. },
  38397. /**
  38398. * Sets the Exposure used in the effect.
  38399. */
  38400. set: function (value) {
  38401. if (this._exposure === value) {
  38402. return;
  38403. }
  38404. this._exposure = value;
  38405. this._updateParameters();
  38406. },
  38407. enumerable: true,
  38408. configurable: true
  38409. });
  38410. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  38411. /**
  38412. * Gets wether the tone mapping effect is enabled.
  38413. */
  38414. get: function () {
  38415. return this._toneMappingEnabled;
  38416. },
  38417. /**
  38418. * Sets wether the tone mapping effect is enabled.
  38419. */
  38420. set: function (value) {
  38421. if (this._toneMappingEnabled === value) {
  38422. return;
  38423. }
  38424. this._toneMappingEnabled = value;
  38425. this._updateParameters();
  38426. },
  38427. enumerable: true,
  38428. configurable: true
  38429. });
  38430. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  38431. /**
  38432. * Gets the contrast used in the effect.
  38433. */
  38434. get: function () {
  38435. return this._contrast;
  38436. },
  38437. /**
  38438. * Sets the contrast used in the effect.
  38439. */
  38440. set: function (value) {
  38441. if (this._contrast === value) {
  38442. return;
  38443. }
  38444. this._contrast = value;
  38445. this._updateParameters();
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  38451. /**
  38452. * Gets the vignette blend mode allowing different kind of effect.
  38453. */
  38454. get: function () {
  38455. return this._vignetteBlendMode;
  38456. },
  38457. /**
  38458. * Sets the vignette blend mode allowing different kind of effect.
  38459. */
  38460. set: function (value) {
  38461. if (this._vignetteBlendMode === value) {
  38462. return;
  38463. }
  38464. this._vignetteBlendMode = value;
  38465. this._updateParameters();
  38466. },
  38467. enumerable: true,
  38468. configurable: true
  38469. });
  38470. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  38471. /**
  38472. * Gets wether the vignette effect is enabled.
  38473. */
  38474. get: function () {
  38475. return this._vignetteEnabled;
  38476. },
  38477. /**
  38478. * Sets wether the vignette effect is enabled.
  38479. */
  38480. set: function (value) {
  38481. if (this._vignetteEnabled === value) {
  38482. return;
  38483. }
  38484. this._vignetteEnabled = value;
  38485. this._updateParameters();
  38486. },
  38487. enumerable: true,
  38488. configurable: true
  38489. });
  38490. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  38491. /**
  38492. * Gets wether the image processing is applied through a post process or not.
  38493. */
  38494. get: function () {
  38495. return this._applyByPostProcess;
  38496. },
  38497. /**
  38498. * Sets wether the image processing is applied through a post process or not.
  38499. */
  38500. set: function (value) {
  38501. if (this._applyByPostProcess === value) {
  38502. return;
  38503. }
  38504. this._applyByPostProcess = value;
  38505. this._updateParameters();
  38506. },
  38507. enumerable: true,
  38508. configurable: true
  38509. });
  38510. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  38511. /**
  38512. * Gets wether the image processing is enabled or not.
  38513. */
  38514. get: function () {
  38515. return this._isEnabled;
  38516. },
  38517. /**
  38518. * Sets wether the image processing is enabled or not.
  38519. */
  38520. set: function (value) {
  38521. if (this._isEnabled === value) {
  38522. return;
  38523. }
  38524. this._isEnabled = value;
  38525. this._updateParameters();
  38526. },
  38527. enumerable: true,
  38528. configurable: true
  38529. });
  38530. /**
  38531. * Method called each time the image processing information changes requires to recompile the effect.
  38532. */
  38533. ImageProcessingConfiguration.prototype._updateParameters = function () {
  38534. this.onUpdateParameters.notifyObservers(this);
  38535. };
  38536. ImageProcessingConfiguration.prototype.getClassName = function () {
  38537. return "ImageProcessingConfiguration";
  38538. };
  38539. /**
  38540. * Prepare the list of uniforms associated with the Image Processing effects.
  38541. * @param uniformsList The list of uniforms used in the effect
  38542. * @param defines the list of defines currently in use
  38543. */
  38544. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  38545. if (defines.EXPOSURE) {
  38546. uniforms.push("exposureLinear");
  38547. }
  38548. if (defines.CONTRAST) {
  38549. uniforms.push("contrast");
  38550. }
  38551. if (defines.COLORGRADING) {
  38552. uniforms.push("colorTransformSettings");
  38553. }
  38554. if (defines.VIGNETTE) {
  38555. uniforms.push("vInverseScreenSize");
  38556. uniforms.push("vignetteSettings1");
  38557. uniforms.push("vignetteSettings2");
  38558. }
  38559. if (defines.COLORCURVES) {
  38560. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  38561. }
  38562. };
  38563. /**
  38564. * Prepare the list of samplers associated with the Image Processing effects.
  38565. * @param uniformsList The list of uniforms used in the effect
  38566. * @param defines the list of defines currently in use
  38567. */
  38568. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  38569. if (defines.COLORGRADING) {
  38570. samplersList.push("txColorTransform");
  38571. }
  38572. };
  38573. /**
  38574. * Prepare the list of defines associated to the shader.
  38575. * @param defines the list of defines to complete
  38576. */
  38577. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  38578. if (forPostProcess === void 0) { forPostProcess = false; }
  38579. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  38580. defines.VIGNETTE = false;
  38581. defines.TONEMAPPING = false;
  38582. defines.CONTRAST = false;
  38583. defines.EXPOSURE = false;
  38584. defines.COLORCURVES = false;
  38585. defines.COLORGRADING = false;
  38586. defines.COLORGRADING3D = false;
  38587. defines.IMAGEPROCESSING = false;
  38588. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  38589. return;
  38590. }
  38591. defines.VIGNETTE = this.vignetteEnabled;
  38592. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  38593. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  38594. defines.TONEMAPPING = this.toneMappingEnabled;
  38595. defines.CONTRAST = (this.contrast !== 1.0);
  38596. defines.EXPOSURE = (this.exposure !== 1.0);
  38597. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  38598. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  38599. if (defines.COLORGRADING) {
  38600. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  38601. }
  38602. else {
  38603. defines.COLORGRADING3D = false;
  38604. }
  38605. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  38606. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  38607. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  38608. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  38609. };
  38610. /**
  38611. * Returns true if all the image processing information are ready.
  38612. */
  38613. ImageProcessingConfiguration.prototype.isReady = function () {
  38614. // Color Grading texure can not be none blocking.
  38615. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  38616. };
  38617. /**
  38618. * Binds the image processing to the shader.
  38619. * @param effect The effect to bind to
  38620. */
  38621. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  38622. if (aspectRatio === void 0) { aspectRatio = 1; }
  38623. // Color Curves
  38624. if (this._colorCurvesEnabled && this.colorCurves) {
  38625. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  38626. }
  38627. // Vignette
  38628. if (this._vignetteEnabled) {
  38629. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  38630. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  38631. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  38632. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  38633. var vignetteScaleX = vignetteScaleY * aspectRatio;
  38634. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  38635. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  38636. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  38637. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  38638. var vignettePower = -2.0 * this.vignetteWeight;
  38639. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  38640. }
  38641. // Exposure
  38642. effect.setFloat("exposureLinear", this.exposure);
  38643. // Contrast
  38644. effect.setFloat("contrast", this.contrast);
  38645. // Color transform settings
  38646. if (this.colorGradingTexture) {
  38647. effect.setTexture("txColorTransform", this.colorGradingTexture);
  38648. var textureSize = this.colorGradingTexture.getSize().height;
  38649. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  38650. 0.5 / textureSize, // textureOffset
  38651. textureSize, // textureSize
  38652. this.colorGradingTexture.level // weight
  38653. );
  38654. }
  38655. };
  38656. /**
  38657. * Clones the current image processing instance.
  38658. * @return The cloned image processing
  38659. */
  38660. ImageProcessingConfiguration.prototype.clone = function () {
  38661. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  38662. };
  38663. /**
  38664. * Serializes the current image processing instance to a json representation.
  38665. * @return a JSON representation
  38666. */
  38667. ImageProcessingConfiguration.prototype.serialize = function () {
  38668. return BABYLON.SerializationHelper.Serialize(this);
  38669. };
  38670. /**
  38671. * Parses the image processing from a json representation.
  38672. * @param source the JSON source to parse
  38673. * @return The parsed image processing
  38674. */
  38675. ImageProcessingConfiguration.Parse = function (source) {
  38676. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  38677. };
  38678. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  38679. /**
  38680. * Used to apply the vignette as a mix with the pixel color.
  38681. */
  38682. get: function () {
  38683. return this._VIGNETTEMODE_MULTIPLY;
  38684. },
  38685. enumerable: true,
  38686. configurable: true
  38687. });
  38688. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  38689. /**
  38690. * Used to apply the vignette as a replacement of the pixel color.
  38691. */
  38692. get: function () {
  38693. return this._VIGNETTEMODE_OPAQUE;
  38694. },
  38695. enumerable: true,
  38696. configurable: true
  38697. });
  38698. // Static constants associated to the image processing.
  38699. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  38700. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  38701. __decorate([
  38702. BABYLON.serializeAsColorCurves()
  38703. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  38704. __decorate([
  38705. BABYLON.serialize()
  38706. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  38707. __decorate([
  38708. BABYLON.serializeAsTexture()
  38709. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  38710. __decorate([
  38711. BABYLON.serialize()
  38712. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  38713. __decorate([
  38714. BABYLON.serialize()
  38715. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  38716. __decorate([
  38717. BABYLON.serialize()
  38718. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  38719. __decorate([
  38720. BABYLON.serialize()
  38721. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  38722. __decorate([
  38723. BABYLON.serialize()
  38724. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  38725. __decorate([
  38726. BABYLON.serialize()
  38727. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  38728. __decorate([
  38729. BABYLON.serialize()
  38730. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  38731. __decorate([
  38732. BABYLON.serialize()
  38733. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  38734. __decorate([
  38735. BABYLON.serialize()
  38736. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  38737. __decorate([
  38738. BABYLON.serialize()
  38739. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  38740. __decorate([
  38741. BABYLON.serializeAsColor4()
  38742. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  38743. __decorate([
  38744. BABYLON.serialize()
  38745. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  38746. __decorate([
  38747. BABYLON.serialize()
  38748. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  38749. __decorate([
  38750. BABYLON.serialize()
  38751. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38752. __decorate([
  38753. BABYLON.serialize()
  38754. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38755. __decorate([
  38756. BABYLON.serialize()
  38757. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38758. return ImageProcessingConfiguration;
  38759. }());
  38760. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38761. })(BABYLON || (BABYLON = {}));
  38762. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38763. "use strict";
  38764. var BABYLON;
  38765. (function (BABYLON) {
  38766. /**
  38767. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38768. * It can help converting any input color in a desired output one. This can then be used to create effects
  38769. * from sepia, black and white to sixties or futuristic rendering...
  38770. *
  38771. * The only supported format is currently 3dl.
  38772. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38773. */
  38774. var ColorGradingTexture = /** @class */ (function (_super) {
  38775. __extends(ColorGradingTexture, _super);
  38776. /**
  38777. * Instantiates a ColorGradingTexture from the following parameters.
  38778. *
  38779. * @param url The location of the color gradind data (currently only supporting 3dl)
  38780. * @param scene The scene the texture will be used in
  38781. */
  38782. function ColorGradingTexture(url, scene) {
  38783. var _this = _super.call(this, scene) || this;
  38784. if (!url) {
  38785. return _this;
  38786. }
  38787. _this._engine = scene.getEngine();
  38788. _this._textureMatrix = BABYLON.Matrix.Identity();
  38789. _this.name = url;
  38790. _this.url = url;
  38791. _this.hasAlpha = false;
  38792. _this.isCube = false;
  38793. _this.is3D = _this._engine.webGLVersion > 1;
  38794. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38795. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38796. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38797. _this.anisotropicFilteringLevel = 1;
  38798. _this._texture = _this._getFromCache(url, true);
  38799. if (!_this._texture) {
  38800. if (!scene.useDelayedTextureLoading) {
  38801. _this.loadTexture();
  38802. }
  38803. else {
  38804. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38805. }
  38806. }
  38807. return _this;
  38808. }
  38809. /**
  38810. * Returns the texture matrix used in most of the material.
  38811. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38812. */
  38813. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38814. return this._textureMatrix;
  38815. };
  38816. /**
  38817. * Occurs when the file being loaded is a .3dl LUT file.
  38818. */
  38819. ColorGradingTexture.prototype.load3dlTexture = function () {
  38820. var engine = this._engine;
  38821. var texture;
  38822. if (engine.webGLVersion === 1) {
  38823. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38824. }
  38825. else {
  38826. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38827. }
  38828. this._texture = texture;
  38829. var callback = function (text) {
  38830. if (typeof text !== "string") {
  38831. return;
  38832. }
  38833. var data = null;
  38834. var tempData = null;
  38835. var line;
  38836. var lines = text.split('\n');
  38837. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38838. var maxColor = 0;
  38839. for (var i = 0; i < lines.length; i++) {
  38840. line = lines[i];
  38841. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38842. continue;
  38843. if (line.indexOf('#') === 0)
  38844. continue;
  38845. var words = line.split(" ");
  38846. if (size === 0) {
  38847. // Number of space + one
  38848. size = words.length;
  38849. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38850. tempData = new Float32Array(size * size * size * 4);
  38851. continue;
  38852. }
  38853. if (size != 0) {
  38854. var r = Math.max(parseInt(words[0]), 0);
  38855. var g = Math.max(parseInt(words[1]), 0);
  38856. var b = Math.max(parseInt(words[2]), 0);
  38857. maxColor = Math.max(r, maxColor);
  38858. maxColor = Math.max(g, maxColor);
  38859. maxColor = Math.max(b, maxColor);
  38860. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38861. if (tempData) {
  38862. tempData[pixelStorageIndex + 0] = r;
  38863. tempData[pixelStorageIndex + 1] = g;
  38864. tempData[pixelStorageIndex + 2] = b;
  38865. }
  38866. pixelIndexSlice++;
  38867. if (pixelIndexSlice % size == 0) {
  38868. pixelIndexH++;
  38869. pixelIndexSlice = 0;
  38870. if (pixelIndexH % size == 0) {
  38871. pixelIndexW++;
  38872. pixelIndexH = 0;
  38873. }
  38874. }
  38875. }
  38876. }
  38877. if (tempData && data) {
  38878. for (var i = 0; i < tempData.length; i++) {
  38879. if (i > 0 && (i + 1) % 4 === 0) {
  38880. data[i] = 255;
  38881. }
  38882. else {
  38883. var value = tempData[i];
  38884. data[i] = (value / maxColor * 255);
  38885. }
  38886. }
  38887. }
  38888. if (texture.is3D) {
  38889. texture.updateSize(size, size, size);
  38890. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38891. }
  38892. else {
  38893. texture.updateSize(size * size, size);
  38894. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38895. }
  38896. };
  38897. var scene = this.getScene();
  38898. if (scene) {
  38899. scene._loadFile(this.url, callback);
  38900. }
  38901. else {
  38902. this._engine._loadFile(this.url, callback);
  38903. }
  38904. return this._texture;
  38905. };
  38906. /**
  38907. * Starts the loading process of the texture.
  38908. */
  38909. ColorGradingTexture.prototype.loadTexture = function () {
  38910. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38911. this.load3dlTexture();
  38912. }
  38913. };
  38914. /**
  38915. * Clones the color gradind texture.
  38916. */
  38917. ColorGradingTexture.prototype.clone = function () {
  38918. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38919. // Base texture
  38920. newTexture.level = this.level;
  38921. return newTexture;
  38922. };
  38923. /**
  38924. * Called during delayed load for textures.
  38925. */
  38926. ColorGradingTexture.prototype.delayLoad = function () {
  38927. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38928. return;
  38929. }
  38930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38931. this._texture = this._getFromCache(this.url, true);
  38932. if (!this._texture) {
  38933. this.loadTexture();
  38934. }
  38935. };
  38936. /**
  38937. * Parses a color grading texture serialized by Babylon.
  38938. * @param parsedTexture The texture information being parsedTexture
  38939. * @param scene The scene to load the texture in
  38940. * @param rootUrl The root url of the data assets to load
  38941. * @return A color gradind texture
  38942. */
  38943. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38944. var texture = null;
  38945. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38946. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38947. texture.name = parsedTexture.name;
  38948. texture.level = parsedTexture.level;
  38949. }
  38950. return texture;
  38951. };
  38952. /**
  38953. * Serializes the LUT texture to json format.
  38954. */
  38955. ColorGradingTexture.prototype.serialize = function () {
  38956. if (!this.name) {
  38957. return null;
  38958. }
  38959. var serializationObject = {};
  38960. serializationObject.name = this.name;
  38961. serializationObject.level = this.level;
  38962. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38963. return serializationObject;
  38964. };
  38965. /**
  38966. * Empty line regex stored for GC.
  38967. */
  38968. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38969. return ColorGradingTexture;
  38970. }(BABYLON.BaseTexture));
  38971. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38972. })(BABYLON || (BABYLON = {}));
  38973. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38974. "use strict";
  38975. var BABYLON;
  38976. (function (BABYLON) {
  38977. /**
  38978. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38979. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38980. * 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;
  38981. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38982. */
  38983. var ColorCurves = /** @class */ (function () {
  38984. function ColorCurves() {
  38985. this._dirty = true;
  38986. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38987. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38988. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38989. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38990. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38991. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38992. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38993. this._globalHue = 30;
  38994. this._globalDensity = 0;
  38995. this._globalSaturation = 0;
  38996. this._globalExposure = 0;
  38997. this._highlightsHue = 30;
  38998. this._highlightsDensity = 0;
  38999. this._highlightsSaturation = 0;
  39000. this._highlightsExposure = 0;
  39001. this._midtonesHue = 30;
  39002. this._midtonesDensity = 0;
  39003. this._midtonesSaturation = 0;
  39004. this._midtonesExposure = 0;
  39005. this._shadowsHue = 30;
  39006. this._shadowsDensity = 0;
  39007. this._shadowsSaturation = 0;
  39008. this._shadowsExposure = 0;
  39009. }
  39010. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  39011. /**
  39012. * Gets the global Hue value.
  39013. * 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).
  39014. */
  39015. get: function () {
  39016. return this._globalHue;
  39017. },
  39018. /**
  39019. * Sets the global Hue value.
  39020. * 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).
  39021. */
  39022. set: function (value) {
  39023. this._globalHue = value;
  39024. this._dirty = true;
  39025. },
  39026. enumerable: true,
  39027. configurable: true
  39028. });
  39029. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  39030. /**
  39031. * Gets the global Density value.
  39032. * 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.
  39033. * Values less than zero provide a filter of opposite hue.
  39034. */
  39035. get: function () {
  39036. return this._globalDensity;
  39037. },
  39038. /**
  39039. * Sets the global Density value.
  39040. * 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.
  39041. * Values less than zero provide a filter of opposite hue.
  39042. */
  39043. set: function (value) {
  39044. this._globalDensity = value;
  39045. this._dirty = true;
  39046. },
  39047. enumerable: true,
  39048. configurable: true
  39049. });
  39050. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  39051. /**
  39052. * Gets the global Saturation value.
  39053. * 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.
  39054. */
  39055. get: function () {
  39056. return this._globalSaturation;
  39057. },
  39058. /**
  39059. * Sets the global Saturation value.
  39060. * 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.
  39061. */
  39062. set: function (value) {
  39063. this._globalSaturation = value;
  39064. this._dirty = true;
  39065. },
  39066. enumerable: true,
  39067. configurable: true
  39068. });
  39069. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  39070. /**
  39071. * Gets the highlights Hue value.
  39072. * 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).
  39073. */
  39074. get: function () {
  39075. return this._highlightsHue;
  39076. },
  39077. /**
  39078. * Sets the highlights Hue value.
  39079. * 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).
  39080. */
  39081. set: function (value) {
  39082. this._highlightsHue = value;
  39083. this._dirty = true;
  39084. },
  39085. enumerable: true,
  39086. configurable: true
  39087. });
  39088. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  39089. /**
  39090. * Gets the highlights Density value.
  39091. * 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.
  39092. * Values less than zero provide a filter of opposite hue.
  39093. */
  39094. get: function () {
  39095. return this._highlightsDensity;
  39096. },
  39097. /**
  39098. * Sets the highlights Density value.
  39099. * 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.
  39100. * Values less than zero provide a filter of opposite hue.
  39101. */
  39102. set: function (value) {
  39103. this._highlightsDensity = value;
  39104. this._dirty = true;
  39105. },
  39106. enumerable: true,
  39107. configurable: true
  39108. });
  39109. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  39110. /**
  39111. * Gets the highlights Saturation value.
  39112. * 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.
  39113. */
  39114. get: function () {
  39115. return this._highlightsSaturation;
  39116. },
  39117. /**
  39118. * Sets the highlights Saturation value.
  39119. * 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.
  39120. */
  39121. set: function (value) {
  39122. this._highlightsSaturation = value;
  39123. this._dirty = true;
  39124. },
  39125. enumerable: true,
  39126. configurable: true
  39127. });
  39128. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  39129. /**
  39130. * Gets the highlights Exposure value.
  39131. * 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.
  39132. */
  39133. get: function () {
  39134. return this._highlightsExposure;
  39135. },
  39136. /**
  39137. * Sets the highlights Exposure value.
  39138. * 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.
  39139. */
  39140. set: function (value) {
  39141. this._highlightsExposure = value;
  39142. this._dirty = true;
  39143. },
  39144. enumerable: true,
  39145. configurable: true
  39146. });
  39147. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  39148. /**
  39149. * Gets the midtones Hue value.
  39150. * 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).
  39151. */
  39152. get: function () {
  39153. return this._midtonesHue;
  39154. },
  39155. /**
  39156. * Sets the midtones Hue value.
  39157. * 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).
  39158. */
  39159. set: function (value) {
  39160. this._midtonesHue = value;
  39161. this._dirty = true;
  39162. },
  39163. enumerable: true,
  39164. configurable: true
  39165. });
  39166. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  39167. /**
  39168. * Gets the midtones Density value.
  39169. * 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.
  39170. * Values less than zero provide a filter of opposite hue.
  39171. */
  39172. get: function () {
  39173. return this._midtonesDensity;
  39174. },
  39175. /**
  39176. * Sets the midtones Density value.
  39177. * 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.
  39178. * Values less than zero provide a filter of opposite hue.
  39179. */
  39180. set: function (value) {
  39181. this._midtonesDensity = value;
  39182. this._dirty = true;
  39183. },
  39184. enumerable: true,
  39185. configurable: true
  39186. });
  39187. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  39188. /**
  39189. * Gets the midtones Saturation value.
  39190. * 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.
  39191. */
  39192. get: function () {
  39193. return this._midtonesSaturation;
  39194. },
  39195. /**
  39196. * Sets the midtones Saturation value.
  39197. * 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.
  39198. */
  39199. set: function (value) {
  39200. this._midtonesSaturation = value;
  39201. this._dirty = true;
  39202. },
  39203. enumerable: true,
  39204. configurable: true
  39205. });
  39206. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  39207. /**
  39208. * Gets the midtones Exposure value.
  39209. * 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.
  39210. */
  39211. get: function () {
  39212. return this._midtonesExposure;
  39213. },
  39214. /**
  39215. * Sets the midtones Exposure value.
  39216. * 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.
  39217. */
  39218. set: function (value) {
  39219. this._midtonesExposure = value;
  39220. this._dirty = true;
  39221. },
  39222. enumerable: true,
  39223. configurable: true
  39224. });
  39225. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  39226. /**
  39227. * Gets the shadows Hue value.
  39228. * 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).
  39229. */
  39230. get: function () {
  39231. return this._shadowsHue;
  39232. },
  39233. /**
  39234. * Sets the shadows Hue value.
  39235. * 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).
  39236. */
  39237. set: function (value) {
  39238. this._shadowsHue = value;
  39239. this._dirty = true;
  39240. },
  39241. enumerable: true,
  39242. configurable: true
  39243. });
  39244. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  39245. /**
  39246. * Gets the shadows Density value.
  39247. * 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.
  39248. * Values less than zero provide a filter of opposite hue.
  39249. */
  39250. get: function () {
  39251. return this._shadowsDensity;
  39252. },
  39253. /**
  39254. * Sets the shadows Density value.
  39255. * 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.
  39256. * Values less than zero provide a filter of opposite hue.
  39257. */
  39258. set: function (value) {
  39259. this._shadowsDensity = value;
  39260. this._dirty = true;
  39261. },
  39262. enumerable: true,
  39263. configurable: true
  39264. });
  39265. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  39266. /**
  39267. * Gets the shadows Saturation value.
  39268. * 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.
  39269. */
  39270. get: function () {
  39271. return this._shadowsSaturation;
  39272. },
  39273. /**
  39274. * Sets the shadows Saturation value.
  39275. * 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.
  39276. */
  39277. set: function (value) {
  39278. this._shadowsSaturation = value;
  39279. this._dirty = true;
  39280. },
  39281. enumerable: true,
  39282. configurable: true
  39283. });
  39284. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  39285. /**
  39286. * Gets the shadows Exposure 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 exposure and negative values decrease exposure.
  39288. */
  39289. get: function () {
  39290. return this._shadowsExposure;
  39291. },
  39292. /**
  39293. * Sets the shadows Exposure 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 exposure and negative values decrease exposure.
  39295. */
  39296. set: function (value) {
  39297. this._shadowsExposure = value;
  39298. this._dirty = true;
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. ColorCurves.prototype.getClassName = function () {
  39304. return "ColorCurves";
  39305. };
  39306. /**
  39307. * Binds the color curves to the shader.
  39308. * @param colorCurves The color curve to bind
  39309. * @param effect The effect to bind to
  39310. */
  39311. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  39312. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  39313. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  39314. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  39315. if (colorCurves._dirty) {
  39316. colorCurves._dirty = false;
  39317. // Fill in global info.
  39318. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  39319. // Compute highlights info.
  39320. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  39321. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  39322. // Compute midtones info.
  39323. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  39324. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  39325. // Compute shadows info.
  39326. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  39327. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  39328. // Compute deltas (neutral is midtones).
  39329. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  39330. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  39331. }
  39332. if (effect) {
  39333. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  39334. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  39335. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  39336. }
  39337. };
  39338. /**
  39339. * Prepare the list of uniforms associated with the ColorCurves effects.
  39340. * @param uniformsList The list of uniforms used in the effect
  39341. */
  39342. ColorCurves.PrepareUniforms = function (uniformsList) {
  39343. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  39344. };
  39345. /**
  39346. * Returns color grading data based on a hue, density, saturation and exposure value.
  39347. * @param filterHue The hue of the color filter.
  39348. * @param filterDensity The density of the color filter.
  39349. * @param saturation The saturation.
  39350. * @param exposure The exposure.
  39351. * @param result The result data container.
  39352. */
  39353. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  39354. if (hue == null) {
  39355. return;
  39356. }
  39357. hue = ColorCurves.clamp(hue, 0, 360);
  39358. density = ColorCurves.clamp(density, -100, 100);
  39359. saturation = ColorCurves.clamp(saturation, -100, 100);
  39360. exposure = ColorCurves.clamp(exposure, -100, 100);
  39361. // Remap the slider/config filter density with non-linear mapping and also scale by half
  39362. // so that the maximum filter density is only 50% control. This provides fine control
  39363. // for small values and reasonable range.
  39364. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  39365. density *= 0.5;
  39366. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  39367. if (density < 0) {
  39368. density *= -1;
  39369. hue = (hue + 180) % 360;
  39370. }
  39371. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  39372. result.scaleToRef(2, result);
  39373. result.a = 1 + 0.01 * saturation;
  39374. };
  39375. /**
  39376. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  39377. * @param value The input slider value in range [-100,100].
  39378. * @returns Adjusted value.
  39379. */
  39380. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  39381. value /= 100;
  39382. var x = Math.abs(value);
  39383. x = Math.pow(x, 2);
  39384. if (value < 0) {
  39385. x *= -1;
  39386. }
  39387. x *= 100;
  39388. return x;
  39389. };
  39390. /**
  39391. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  39392. * @param hue The hue (H) input.
  39393. * @param saturation The saturation (S) input.
  39394. * @param brightness The brightness (B) input.
  39395. * @result An RGBA color represented as Vector4.
  39396. */
  39397. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  39398. var h = ColorCurves.clamp(hue, 0, 360);
  39399. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  39400. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  39401. if (s === 0) {
  39402. result.r = v;
  39403. result.g = v;
  39404. result.b = v;
  39405. }
  39406. else {
  39407. // sector 0 to 5
  39408. h /= 60;
  39409. var i = Math.floor(h);
  39410. // fractional part of h
  39411. var f = h - i;
  39412. var p = v * (1 - s);
  39413. var q = v * (1 - s * f);
  39414. var t = v * (1 - s * (1 - f));
  39415. switch (i) {
  39416. case 0:
  39417. result.r = v;
  39418. result.g = t;
  39419. result.b = p;
  39420. break;
  39421. case 1:
  39422. result.r = q;
  39423. result.g = v;
  39424. result.b = p;
  39425. break;
  39426. case 2:
  39427. result.r = p;
  39428. result.g = v;
  39429. result.b = t;
  39430. break;
  39431. case 3:
  39432. result.r = p;
  39433. result.g = q;
  39434. result.b = v;
  39435. break;
  39436. case 4:
  39437. result.r = t;
  39438. result.g = p;
  39439. result.b = v;
  39440. break;
  39441. default:// case 5:
  39442. result.r = v;
  39443. result.g = p;
  39444. result.b = q;
  39445. break;
  39446. }
  39447. }
  39448. result.a = 1;
  39449. };
  39450. /**
  39451. * Returns a value clamped between min and max
  39452. * @param value The value to clamp
  39453. * @param min The minimum of value
  39454. * @param max The maximum of value
  39455. * @returns The clamped value.
  39456. */
  39457. ColorCurves.clamp = function (value, min, max) {
  39458. return Math.min(Math.max(value, min), max);
  39459. };
  39460. /**
  39461. * Clones the current color curve instance.
  39462. * @return The cloned curves
  39463. */
  39464. ColorCurves.prototype.clone = function () {
  39465. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  39466. };
  39467. /**
  39468. * Serializes the current color curve instance to a json representation.
  39469. * @return a JSON representation
  39470. */
  39471. ColorCurves.prototype.serialize = function () {
  39472. return BABYLON.SerializationHelper.Serialize(this);
  39473. };
  39474. /**
  39475. * Parses the color curve from a json representation.
  39476. * @param source the JSON source to parse
  39477. * @return The parsed curves
  39478. */
  39479. ColorCurves.Parse = function (source) {
  39480. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  39481. };
  39482. __decorate([
  39483. BABYLON.serialize()
  39484. ], ColorCurves.prototype, "_globalHue", void 0);
  39485. __decorate([
  39486. BABYLON.serialize()
  39487. ], ColorCurves.prototype, "_globalDensity", void 0);
  39488. __decorate([
  39489. BABYLON.serialize()
  39490. ], ColorCurves.prototype, "_globalSaturation", void 0);
  39491. __decorate([
  39492. BABYLON.serialize()
  39493. ], ColorCurves.prototype, "_globalExposure", void 0);
  39494. __decorate([
  39495. BABYLON.serialize()
  39496. ], ColorCurves.prototype, "_highlightsHue", void 0);
  39497. __decorate([
  39498. BABYLON.serialize()
  39499. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  39500. __decorate([
  39501. BABYLON.serialize()
  39502. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  39503. __decorate([
  39504. BABYLON.serialize()
  39505. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  39506. __decorate([
  39507. BABYLON.serialize()
  39508. ], ColorCurves.prototype, "_midtonesHue", void 0);
  39509. __decorate([
  39510. BABYLON.serialize()
  39511. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  39512. __decorate([
  39513. BABYLON.serialize()
  39514. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  39515. __decorate([
  39516. BABYLON.serialize()
  39517. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  39518. return ColorCurves;
  39519. }());
  39520. BABYLON.ColorCurves = ColorCurves;
  39521. })(BABYLON || (BABYLON = {}));
  39522. //# sourceMappingURL=babylon.colorCurves.js.map
  39523. "use strict";
  39524. //# sourceMappingURL=babylon.behavior.js.map
  39525. "use strict";
  39526. var BABYLON;
  39527. (function (BABYLON) {
  39528. /**
  39529. * "Static Class" containing the most commonly used helper while dealing with material for
  39530. * rendering purpose.
  39531. *
  39532. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  39533. *
  39534. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  39535. */
  39536. var MaterialHelper = /** @class */ (function () {
  39537. function MaterialHelper() {
  39538. }
  39539. /**
  39540. * Bind the current view position to an effect.
  39541. * @param effect The effect to be bound
  39542. * @param scene The scene the eyes position is used from
  39543. */
  39544. MaterialHelper.BindEyePosition = function (effect, scene) {
  39545. if (scene._forcedViewPosition) {
  39546. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  39547. return;
  39548. }
  39549. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  39550. };
  39551. /**
  39552. * Helps preparing the defines values about the UVs in used in the effect.
  39553. * UVs are shared as much as we can accross chanels in the shaders.
  39554. * @param texture The texture we are preparing the UVs for
  39555. * @param defines The defines to update
  39556. * @param key The chanel key "diffuse", "specular"... used in the shader
  39557. */
  39558. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  39559. defines._needUVs = true;
  39560. defines[key] = true;
  39561. if (texture.getTextureMatrix().isIdentity(true)) {
  39562. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  39563. if (texture.coordinatesIndex === 0) {
  39564. defines["MAINUV1"] = true;
  39565. }
  39566. else {
  39567. defines["MAINUV2"] = true;
  39568. }
  39569. }
  39570. else {
  39571. defines[key + "DIRECTUV"] = 0;
  39572. }
  39573. };
  39574. /**
  39575. * Binds a texture matrix value to its corrsponding uniform
  39576. * @param texture The texture to bind the matrix for
  39577. * @param uniformBuffer The uniform buffer receivin the data
  39578. * @param key The chanel key "diffuse", "specular"... used in the shader
  39579. */
  39580. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  39581. var matrix = texture.getTextureMatrix();
  39582. if (!matrix.isIdentity(true)) {
  39583. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  39584. }
  39585. };
  39586. /**
  39587. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  39588. * @param mesh defines the current mesh
  39589. * @param scene defines the current scene
  39590. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  39591. * @param pointsCloud defines if point cloud rendering has to be turned on
  39592. * @param fogEnabled defines if fog has to be turned on
  39593. * @param alphaTest defines if alpha testing has to be turned on
  39594. * @param defines defines the current list of defines
  39595. */
  39596. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  39597. if (defines._areMiscDirty) {
  39598. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  39599. defines["POINTSIZE"] = pointsCloud;
  39600. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  39601. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  39602. defines["ALPHATEST"] = alphaTest;
  39603. }
  39604. };
  39605. /**
  39606. * Helper used to prepare the list of defines associated with frame values for shader compilation
  39607. * @param scene defines the current scene
  39608. * @param engine defines the current engine
  39609. * @param defines specifies the list of active defines
  39610. * @param useInstances defines if instances have to be turned on
  39611. * @param useClipPlane defines if clip plane have to be turned on
  39612. */
  39613. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  39614. if (useClipPlane === void 0) { useClipPlane = null; }
  39615. var changed = false;
  39616. if (useClipPlane == null) {
  39617. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  39618. }
  39619. if (defines["CLIPPLANE"] !== useClipPlane) {
  39620. defines["CLIPPLANE"] = useClipPlane;
  39621. changed = true;
  39622. }
  39623. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  39624. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  39625. changed = true;
  39626. }
  39627. if (defines["INSTANCES"] !== useInstances) {
  39628. defines["INSTANCES"] = useInstances;
  39629. changed = true;
  39630. }
  39631. if (changed) {
  39632. defines.markAsUnprocessed();
  39633. }
  39634. };
  39635. /**
  39636. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  39637. * @param mesh The mesh containing the geometry data we will draw
  39638. * @param defines The defines to update
  39639. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  39640. * @param useBones Precise whether bones should be used or not (override mesh info)
  39641. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  39642. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  39643. * @returns false if defines are considered not dirty and have not been checked
  39644. */
  39645. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  39646. if (useMorphTargets === void 0) { useMorphTargets = false; }
  39647. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  39648. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  39649. return false;
  39650. }
  39651. defines._normals = defines._needNormals;
  39652. defines._uvs = defines._needUVs;
  39653. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  39654. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39655. defines["TANGENT"] = true;
  39656. }
  39657. if (defines._needUVs) {
  39658. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  39659. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  39660. }
  39661. else {
  39662. defines["UV1"] = false;
  39663. defines["UV2"] = false;
  39664. }
  39665. if (useVertexColor) {
  39666. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  39667. defines["VERTEXCOLOR"] = hasVertexColors;
  39668. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  39669. }
  39670. if (useBones) {
  39671. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39672. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  39673. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  39674. }
  39675. else {
  39676. defines["NUM_BONE_INFLUENCERS"] = 0;
  39677. defines["BonesPerMesh"] = 0;
  39678. }
  39679. }
  39680. if (useMorphTargets) {
  39681. var manager = mesh.morphTargetManager;
  39682. if (manager) {
  39683. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  39684. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  39685. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  39686. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  39687. }
  39688. else {
  39689. defines["MORPHTARGETS_TANGENT"] = false;
  39690. defines["MORPHTARGETS_NORMAL"] = false;
  39691. defines["MORPHTARGETS"] = false;
  39692. defines["NUM_MORPH_INFLUENCERS"] = 0;
  39693. }
  39694. }
  39695. return true;
  39696. };
  39697. /**
  39698. * Prepares the defines related to the light information passed in parameter
  39699. * @param scene The scene we are intending to draw
  39700. * @param mesh The mesh the effect is compiling for
  39701. * @param defines The defines to update
  39702. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  39703. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  39704. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  39705. * @returns true if normals will be required for the rest of the effect
  39706. */
  39707. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  39708. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39709. if (disableLighting === void 0) { disableLighting = false; }
  39710. if (!defines._areLightsDirty) {
  39711. return defines._needNormals;
  39712. }
  39713. var lightIndex = 0;
  39714. var needNormals = false;
  39715. var needRebuild = false;
  39716. var lightmapMode = false;
  39717. var shadowEnabled = false;
  39718. var specularEnabled = false;
  39719. if (scene.lightsEnabled && !disableLighting) {
  39720. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  39721. var light = _a[_i];
  39722. needNormals = true;
  39723. if (defines["LIGHT" + lightIndex] === undefined) {
  39724. needRebuild = true;
  39725. }
  39726. defines["LIGHT" + lightIndex] = true;
  39727. defines["SPOTLIGHT" + lightIndex] = false;
  39728. defines["HEMILIGHT" + lightIndex] = false;
  39729. defines["POINTLIGHT" + lightIndex] = false;
  39730. defines["DIRLIGHT" + lightIndex] = false;
  39731. var type;
  39732. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  39733. type = "SPOTLIGHT" + lightIndex;
  39734. var spotLight = light;
  39735. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  39736. }
  39737. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  39738. type = "HEMILIGHT" + lightIndex;
  39739. }
  39740. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  39741. type = "POINTLIGHT" + lightIndex;
  39742. }
  39743. else {
  39744. type = "DIRLIGHT" + lightIndex;
  39745. }
  39746. defines[type] = true;
  39747. // Specular
  39748. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  39749. specularEnabled = true;
  39750. }
  39751. // Shadows
  39752. defines["SHADOW" + lightIndex] = false;
  39753. defines["SHADOWPCF" + lightIndex] = false;
  39754. defines["SHADOWPCSS" + lightIndex] = false;
  39755. defines["SHADOWPOISSON" + lightIndex] = false;
  39756. defines["SHADOWESM" + lightIndex] = false;
  39757. defines["SHADOWCUBE" + lightIndex] = false;
  39758. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39759. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39760. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39761. var shadowGenerator = light.getShadowGenerator();
  39762. if (shadowGenerator) {
  39763. shadowEnabled = true;
  39764. shadowGenerator.prepareDefines(defines, lightIndex);
  39765. }
  39766. }
  39767. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39768. lightmapMode = true;
  39769. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39770. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39771. }
  39772. else {
  39773. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39774. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39775. }
  39776. lightIndex++;
  39777. if (lightIndex === maxSimultaneousLights)
  39778. break;
  39779. }
  39780. }
  39781. defines["SPECULARTERM"] = specularEnabled;
  39782. defines["SHADOWS"] = shadowEnabled;
  39783. // Resetting all other lights if any
  39784. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39785. if (defines["LIGHT" + index] !== undefined) {
  39786. defines["LIGHT" + index] = false;
  39787. defines["HEMILIGHT" + lightIndex] = false;
  39788. defines["POINTLIGHT" + lightIndex] = false;
  39789. defines["DIRLIGHT" + lightIndex] = false;
  39790. defines["SPOTLIGHT" + lightIndex] = false;
  39791. defines["SHADOW" + lightIndex] = false;
  39792. }
  39793. }
  39794. var caps = scene.getEngine().getCaps();
  39795. if (defines["SHADOWFLOAT"] === undefined) {
  39796. needRebuild = true;
  39797. }
  39798. defines["SHADOWFLOAT"] = shadowEnabled &&
  39799. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39800. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39801. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39802. if (needRebuild) {
  39803. defines.rebuild();
  39804. }
  39805. return needNormals;
  39806. };
  39807. /**
  39808. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39809. * that won t be acctive due to defines being turned off.
  39810. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39811. * @param samplersList The samplers list
  39812. * @param defines The defines helping in the list generation
  39813. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39814. */
  39815. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39816. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39817. var uniformsList;
  39818. var uniformBuffersList = null;
  39819. if (uniformsListOrOptions.uniformsNames) {
  39820. var options = uniformsListOrOptions;
  39821. uniformsList = options.uniformsNames;
  39822. uniformBuffersList = options.uniformBuffersNames;
  39823. samplersList = options.samplers;
  39824. defines = options.defines;
  39825. maxSimultaneousLights = options.maxSimultaneousLights;
  39826. }
  39827. else {
  39828. uniformsList = uniformsListOrOptions;
  39829. if (!samplersList) {
  39830. samplersList = [];
  39831. }
  39832. }
  39833. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39834. if (!defines["LIGHT" + lightIndex]) {
  39835. break;
  39836. }
  39837. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39838. if (uniformBuffersList) {
  39839. uniformBuffersList.push("Light" + lightIndex);
  39840. }
  39841. samplersList.push("shadowSampler" + lightIndex);
  39842. samplersList.push("depthSampler" + lightIndex);
  39843. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39844. samplersList.push("projectionLightSampler" + lightIndex);
  39845. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39846. }
  39847. }
  39848. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39849. uniformsList.push("morphTargetInfluences");
  39850. }
  39851. };
  39852. /**
  39853. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39854. * @param defines The defines to update while falling back
  39855. * @param fallbacks The authorized effect fallbacks
  39856. * @param maxSimultaneousLights The maximum number of lights allowed
  39857. * @param rank the current rank of the Effect
  39858. * @returns The newly affected rank
  39859. */
  39860. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39861. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39862. if (rank === void 0) { rank = 0; }
  39863. var lightFallbackRank = 0;
  39864. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39865. if (!defines["LIGHT" + lightIndex]) {
  39866. break;
  39867. }
  39868. if (lightIndex > 0) {
  39869. lightFallbackRank = rank + lightIndex;
  39870. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39871. }
  39872. if (!defines["SHADOWS"]) {
  39873. if (defines["SHADOW" + lightIndex]) {
  39874. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39875. }
  39876. if (defines["SHADOWPCF" + lightIndex]) {
  39877. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39878. }
  39879. if (defines["SHADOWPCSS" + lightIndex]) {
  39880. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39881. }
  39882. if (defines["SHADOWPOISSON" + lightIndex]) {
  39883. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39884. }
  39885. if (defines["SHADOWESM" + lightIndex]) {
  39886. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39887. }
  39888. }
  39889. }
  39890. return lightFallbackRank++;
  39891. };
  39892. /**
  39893. * Prepares the list of attributes required for morph targets according to the effect defines.
  39894. * @param attribs The current list of supported attribs
  39895. * @param mesh The mesh to prepare the morph targets attributes for
  39896. * @param defines The current Defines of the effect
  39897. */
  39898. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39899. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39900. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39901. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39902. var manager = mesh.morphTargetManager;
  39903. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39904. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39905. for (var index = 0; index < influencers; index++) {
  39906. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39907. if (normal) {
  39908. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39909. }
  39910. if (tangent) {
  39911. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39912. }
  39913. if (attribs.length > maxAttributesCount) {
  39914. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39915. }
  39916. }
  39917. }
  39918. };
  39919. /**
  39920. * Prepares the list of attributes required for bones according to the effect defines.
  39921. * @param attribs The current list of supported attribs
  39922. * @param mesh The mesh to prepare the bones attributes for
  39923. * @param defines The current Defines of the effect
  39924. * @param fallbacks The current efffect fallback strategy
  39925. */
  39926. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39927. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39928. fallbacks.addCPUSkinningFallback(0, mesh);
  39929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39931. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39932. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39933. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39934. }
  39935. }
  39936. };
  39937. /**
  39938. * Prepares the list of attributes required for instances according to the effect defines.
  39939. * @param attribs The current list of supported attribs
  39940. * @param defines The current Defines of the effect
  39941. */
  39942. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39943. if (defines["INSTANCES"]) {
  39944. attribs.push("world0");
  39945. attribs.push("world1");
  39946. attribs.push("world2");
  39947. attribs.push("world3");
  39948. }
  39949. };
  39950. /**
  39951. * Binds the light shadow information to the effect for the given mesh.
  39952. * @param light The light containing the generator
  39953. * @param scene The scene the lights belongs to
  39954. * @param mesh The mesh we are binding the information to render
  39955. * @param lightIndex The light index in the effect used to render the mesh
  39956. * @param effect The effect we are binding the data to
  39957. */
  39958. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39959. if (light.shadowEnabled && mesh.receiveShadows) {
  39960. var shadowGenerator = light.getShadowGenerator();
  39961. if (shadowGenerator) {
  39962. shadowGenerator.bindShadowLight(lightIndex, effect);
  39963. }
  39964. }
  39965. };
  39966. /**
  39967. * Binds the light information to the effect.
  39968. * @param light The light containing the generator
  39969. * @param effect The effect we are binding the data to
  39970. * @param lightIndex The light index in the effect used to render
  39971. */
  39972. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39973. light.transferToEffect(effect, lightIndex + "");
  39974. };
  39975. /**
  39976. * Binds the lights information from the scene to the effect for the given mesh.
  39977. * @param scene The scene the lights belongs to
  39978. * @param mesh The mesh we are binding the information to render
  39979. * @param effect The effect we are binding the data to
  39980. * @param defines The generated defines for the effect
  39981. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39982. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39983. */
  39984. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39985. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39986. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39987. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39988. for (var i = 0; i < len; i++) {
  39989. var light = mesh._lightSources[i];
  39990. var iAsString = i.toString();
  39991. var scaledIntensity = light.getScaledIntensity();
  39992. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39993. MaterialHelper.BindLightProperties(light, effect, i);
  39994. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39995. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39996. if (defines["SPECULARTERM"]) {
  39997. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39998. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39999. }
  40000. // Shadows
  40001. if (scene.shadowsEnabled) {
  40002. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  40003. }
  40004. light._uniformBuffer.update();
  40005. }
  40006. };
  40007. /**
  40008. * Binds the fog information from the scene to the effect for the given mesh.
  40009. * @param scene The scene the lights belongs to
  40010. * @param mesh The mesh we are binding the information to render
  40011. * @param effect The effect we are binding the data to
  40012. */
  40013. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  40014. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  40015. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  40016. effect.setColor3("vFogColor", scene.fogColor);
  40017. }
  40018. };
  40019. /**
  40020. * Binds the bones information from the mesh to the effect.
  40021. * @param mesh The mesh we are binding the information to render
  40022. * @param effect The effect we are binding the data to
  40023. */
  40024. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  40025. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  40026. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  40027. if (matrices && effect) {
  40028. effect.setMatrices("mBones", matrices);
  40029. }
  40030. }
  40031. };
  40032. /**
  40033. * Binds the morph targets information from the mesh to the effect.
  40034. * @param abstractMesh The mesh we are binding the information to render
  40035. * @param effect The effect we are binding the data to
  40036. */
  40037. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  40038. var manager = abstractMesh.morphTargetManager;
  40039. if (!abstractMesh || !manager) {
  40040. return;
  40041. }
  40042. effect.setFloatArray("morphTargetInfluences", manager.influences);
  40043. };
  40044. /**
  40045. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  40046. * @param defines The generated defines used in the effect
  40047. * @param effect The effect we are binding the data to
  40048. * @param scene The scene we are willing to render with logarithmic scale for
  40049. */
  40050. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  40051. if (defines["LOGARITHMICDEPTH"]) {
  40052. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  40053. }
  40054. };
  40055. /**
  40056. * Binds the clip plane information from the scene to the effect.
  40057. * @param scene The scene the clip plane information are extracted from
  40058. * @param effect The effect we are binding the data to
  40059. */
  40060. MaterialHelper.BindClipPlane = function (effect, scene) {
  40061. if (scene.clipPlane) {
  40062. var clipPlane = scene.clipPlane;
  40063. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  40064. }
  40065. };
  40066. return MaterialHelper;
  40067. }());
  40068. BABYLON.MaterialHelper = MaterialHelper;
  40069. })(BABYLON || (BABYLON = {}));
  40070. //# sourceMappingURL=babylon.materialHelper.js.map
  40071. "use strict";
  40072. var BABYLON;
  40073. (function (BABYLON) {
  40074. var PushMaterial = /** @class */ (function (_super) {
  40075. __extends(PushMaterial, _super);
  40076. function PushMaterial(name, scene) {
  40077. var _this = _super.call(this, name, scene) || this;
  40078. _this._normalMatrix = new BABYLON.Matrix();
  40079. _this.storeEffectOnSubMeshes = true;
  40080. return _this;
  40081. }
  40082. PushMaterial.prototype.getEffect = function () {
  40083. return this._activeEffect;
  40084. };
  40085. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  40086. if (!mesh) {
  40087. return false;
  40088. }
  40089. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  40090. return true;
  40091. }
  40092. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  40093. };
  40094. /**
  40095. * Binds the given world matrix to the active effect
  40096. *
  40097. * @param world the matrix to bind
  40098. */
  40099. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40100. this._activeEffect.setMatrix("world", world);
  40101. };
  40102. /**
  40103. * Binds the given normal matrix to the active effect
  40104. *
  40105. * @param normalMatrix the matrix to bind
  40106. */
  40107. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  40108. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  40109. };
  40110. PushMaterial.prototype.bind = function (world, mesh) {
  40111. if (!mesh) {
  40112. return;
  40113. }
  40114. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  40115. };
  40116. PushMaterial.prototype._afterBind = function (mesh, effect) {
  40117. if (effect === void 0) { effect = null; }
  40118. _super.prototype._afterBind.call(this, mesh);
  40119. this.getScene()._cachedEffect = effect;
  40120. };
  40121. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  40122. if (visibility === void 0) { visibility = 1; }
  40123. return scene.isCachedMaterialInvalid(this, effect, visibility);
  40124. };
  40125. return PushMaterial;
  40126. }(BABYLON.Material));
  40127. BABYLON.PushMaterial = PushMaterial;
  40128. })(BABYLON || (BABYLON = {}));
  40129. //# sourceMappingURL=babylon.pushMaterial.js.map
  40130. "use strict";
  40131. var BABYLON;
  40132. (function (BABYLON) {
  40133. /** @ignore */
  40134. var StandardMaterialDefines = /** @class */ (function (_super) {
  40135. __extends(StandardMaterialDefines, _super);
  40136. function StandardMaterialDefines() {
  40137. var _this = _super.call(this) || this;
  40138. _this.MAINUV1 = false;
  40139. _this.MAINUV2 = false;
  40140. _this.DIFFUSE = false;
  40141. _this.DIFFUSEDIRECTUV = 0;
  40142. _this.AMBIENT = false;
  40143. _this.AMBIENTDIRECTUV = 0;
  40144. _this.OPACITY = false;
  40145. _this.OPACITYDIRECTUV = 0;
  40146. _this.OPACITYRGB = false;
  40147. _this.REFLECTION = false;
  40148. _this.EMISSIVE = false;
  40149. _this.EMISSIVEDIRECTUV = 0;
  40150. _this.SPECULAR = false;
  40151. _this.SPECULARDIRECTUV = 0;
  40152. _this.BUMP = false;
  40153. _this.BUMPDIRECTUV = 0;
  40154. _this.PARALLAX = false;
  40155. _this.PARALLAXOCCLUSION = false;
  40156. _this.SPECULAROVERALPHA = false;
  40157. _this.CLIPPLANE = false;
  40158. _this.ALPHATEST = false;
  40159. _this.DEPTHPREPASS = false;
  40160. _this.ALPHAFROMDIFFUSE = false;
  40161. _this.POINTSIZE = false;
  40162. _this.FOG = false;
  40163. _this.SPECULARTERM = false;
  40164. _this.DIFFUSEFRESNEL = false;
  40165. _this.OPACITYFRESNEL = false;
  40166. _this.REFLECTIONFRESNEL = false;
  40167. _this.REFRACTIONFRESNEL = false;
  40168. _this.EMISSIVEFRESNEL = false;
  40169. _this.FRESNEL = false;
  40170. _this.NORMAL = false;
  40171. _this.UV1 = false;
  40172. _this.UV2 = false;
  40173. _this.VERTEXCOLOR = false;
  40174. _this.VERTEXALPHA = false;
  40175. _this.NUM_BONE_INFLUENCERS = 0;
  40176. _this.BonesPerMesh = 0;
  40177. _this.INSTANCES = false;
  40178. _this.GLOSSINESS = false;
  40179. _this.ROUGHNESS = false;
  40180. _this.EMISSIVEASILLUMINATION = false;
  40181. _this.LINKEMISSIVEWITHDIFFUSE = false;
  40182. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  40183. _this.LIGHTMAP = false;
  40184. _this.LIGHTMAPDIRECTUV = 0;
  40185. _this.OBJECTSPACE_NORMALMAP = false;
  40186. _this.USELIGHTMAPASSHADOWMAP = false;
  40187. _this.REFLECTIONMAP_3D = false;
  40188. _this.REFLECTIONMAP_SPHERICAL = false;
  40189. _this.REFLECTIONMAP_PLANAR = false;
  40190. _this.REFLECTIONMAP_CUBIC = false;
  40191. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40192. _this.REFLECTIONMAP_PROJECTION = false;
  40193. _this.REFLECTIONMAP_SKYBOX = false;
  40194. _this.REFLECTIONMAP_EXPLICIT = false;
  40195. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40196. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40197. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40198. _this.INVERTCUBICMAP = false;
  40199. _this.LOGARITHMICDEPTH = false;
  40200. _this.REFRACTION = false;
  40201. _this.REFRACTIONMAP_3D = false;
  40202. _this.REFLECTIONOVERALPHA = false;
  40203. _this.TWOSIDEDLIGHTING = false;
  40204. _this.SHADOWFLOAT = false;
  40205. _this.MORPHTARGETS = false;
  40206. _this.MORPHTARGETS_NORMAL = false;
  40207. _this.MORPHTARGETS_TANGENT = false;
  40208. _this.NUM_MORPH_INFLUENCERS = 0;
  40209. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  40210. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  40211. _this.IMAGEPROCESSING = false;
  40212. _this.VIGNETTE = false;
  40213. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40214. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40215. _this.TONEMAPPING = false;
  40216. _this.CONTRAST = false;
  40217. _this.COLORCURVES = false;
  40218. _this.COLORGRADING = false;
  40219. _this.COLORGRADING3D = false;
  40220. _this.SAMPLER3DGREENDEPTH = false;
  40221. _this.SAMPLER3DBGRMAP = false;
  40222. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40223. _this.EXPOSURE = false;
  40224. _this.rebuild();
  40225. return _this;
  40226. }
  40227. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  40228. var modes = [
  40229. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  40230. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  40231. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  40232. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  40233. ];
  40234. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  40235. var mode = modes_1[_i];
  40236. this[mode] = (mode === modeToEnable);
  40237. }
  40238. };
  40239. return StandardMaterialDefines;
  40240. }(BABYLON.MaterialDefines));
  40241. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  40242. var StandardMaterial = /** @class */ (function (_super) {
  40243. __extends(StandardMaterial, _super);
  40244. function StandardMaterial(name, scene) {
  40245. var _this = _super.call(this, name, scene) || this;
  40246. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  40247. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  40248. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  40249. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40250. _this.specularPower = 64;
  40251. _this._useAlphaFromDiffuseTexture = false;
  40252. _this._useEmissiveAsIllumination = false;
  40253. _this._linkEmissiveWithDiffuse = false;
  40254. _this._useSpecularOverAlpha = false;
  40255. _this._useReflectionOverAlpha = false;
  40256. _this._disableLighting = false;
  40257. _this._useObjectSpaceNormalMap = false;
  40258. _this._useParallax = false;
  40259. _this._useParallaxOcclusion = false;
  40260. _this.parallaxScaleBias = 0.05;
  40261. _this._roughness = 0;
  40262. _this.indexOfRefraction = 0.98;
  40263. _this.invertRefractionY = true;
  40264. _this._useLightmapAsShadowmap = false;
  40265. _this._useReflectionFresnelFromSpecular = false;
  40266. _this._useGlossinessFromSpecularMapAlpha = false;
  40267. _this._maxSimultaneousLights = 4;
  40268. /**
  40269. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40270. */
  40271. _this._invertNormalMapX = false;
  40272. /**
  40273. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40274. */
  40275. _this._invertNormalMapY = false;
  40276. /**
  40277. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40278. */
  40279. _this._twoSidedLighting = false;
  40280. _this._renderTargets = new BABYLON.SmartArray(16);
  40281. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  40282. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40283. // Setup the default processing configuration to the scene.
  40284. _this._attachImageProcessingConfiguration(null);
  40285. _this.getRenderTargetTextures = function () {
  40286. _this._renderTargets.reset();
  40287. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40288. _this._renderTargets.push(_this._reflectionTexture);
  40289. }
  40290. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40291. _this._renderTargets.push(_this._refractionTexture);
  40292. }
  40293. return _this._renderTargets;
  40294. };
  40295. return _this;
  40296. }
  40297. ;
  40298. ;
  40299. ;
  40300. ;
  40301. ;
  40302. ;
  40303. ;
  40304. ;
  40305. ;
  40306. ;
  40307. ;
  40308. ;
  40309. ;
  40310. ;
  40311. ;
  40312. ;
  40313. ;
  40314. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  40315. /**
  40316. * Gets the image processing configuration used either in this material.
  40317. */
  40318. get: function () {
  40319. return this._imageProcessingConfiguration;
  40320. },
  40321. /**
  40322. * Sets the Default image processing configuration used either in the this material.
  40323. *
  40324. * If sets to null, the scene one is in use.
  40325. */
  40326. set: function (value) {
  40327. this._attachImageProcessingConfiguration(value);
  40328. // Ensure the effect will be rebuilt.
  40329. this._markAllSubMeshesAsTexturesDirty();
  40330. },
  40331. enumerable: true,
  40332. configurable: true
  40333. });
  40334. /**
  40335. * Attaches a new image processing configuration to the Standard Material.
  40336. * @param configuration
  40337. */
  40338. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40339. var _this = this;
  40340. if (configuration === this._imageProcessingConfiguration) {
  40341. return;
  40342. }
  40343. // Detaches observer.
  40344. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40345. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40346. }
  40347. // Pick the scene configuration if needed.
  40348. if (!configuration) {
  40349. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40350. }
  40351. else {
  40352. this._imageProcessingConfiguration = configuration;
  40353. }
  40354. // Attaches observer.
  40355. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40356. _this._markAllSubMeshesAsImageProcessingDirty();
  40357. });
  40358. };
  40359. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  40360. /**
  40361. * Gets wether the color curves effect is enabled.
  40362. */
  40363. get: function () {
  40364. return this.imageProcessingConfiguration.colorCurvesEnabled;
  40365. },
  40366. /**
  40367. * Sets wether the color curves effect is enabled.
  40368. */
  40369. set: function (value) {
  40370. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  40371. },
  40372. enumerable: true,
  40373. configurable: true
  40374. });
  40375. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  40376. /**
  40377. * Gets wether the color grading effect is enabled.
  40378. */
  40379. get: function () {
  40380. return this.imageProcessingConfiguration.colorGradingEnabled;
  40381. },
  40382. /**
  40383. * Gets wether the color grading effect is enabled.
  40384. */
  40385. set: function (value) {
  40386. this.imageProcessingConfiguration.colorGradingEnabled = value;
  40387. },
  40388. enumerable: true,
  40389. configurable: true
  40390. });
  40391. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  40392. /**
  40393. * Gets wether tonemapping is enabled or not.
  40394. */
  40395. get: function () {
  40396. return this._imageProcessingConfiguration.toneMappingEnabled;
  40397. },
  40398. /**
  40399. * Sets wether tonemapping is enabled or not
  40400. */
  40401. set: function (value) {
  40402. this._imageProcessingConfiguration.toneMappingEnabled = value;
  40403. },
  40404. enumerable: true,
  40405. configurable: true
  40406. });
  40407. ;
  40408. ;
  40409. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  40410. /**
  40411. * The camera exposure used on this material.
  40412. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40413. * This corresponds to a photographic exposure.
  40414. */
  40415. get: function () {
  40416. return this._imageProcessingConfiguration.exposure;
  40417. },
  40418. /**
  40419. * The camera exposure used on this material.
  40420. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  40421. * This corresponds to a photographic exposure.
  40422. */
  40423. set: function (value) {
  40424. this._imageProcessingConfiguration.exposure = value;
  40425. },
  40426. enumerable: true,
  40427. configurable: true
  40428. });
  40429. ;
  40430. ;
  40431. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  40432. /**
  40433. * Gets The camera contrast used on this material.
  40434. */
  40435. get: function () {
  40436. return this._imageProcessingConfiguration.contrast;
  40437. },
  40438. /**
  40439. * Sets The camera contrast used on this material.
  40440. */
  40441. set: function (value) {
  40442. this._imageProcessingConfiguration.contrast = value;
  40443. },
  40444. enumerable: true,
  40445. configurable: true
  40446. });
  40447. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  40448. /**
  40449. * Gets the Color Grading 2D Lookup Texture.
  40450. */
  40451. get: function () {
  40452. return this._imageProcessingConfiguration.colorGradingTexture;
  40453. },
  40454. /**
  40455. * Sets the Color Grading 2D Lookup Texture.
  40456. */
  40457. set: function (value) {
  40458. this._imageProcessingConfiguration.colorGradingTexture = value;
  40459. },
  40460. enumerable: true,
  40461. configurable: true
  40462. });
  40463. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  40464. /**
  40465. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40466. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40467. * 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;
  40468. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40469. */
  40470. get: function () {
  40471. return this._imageProcessingConfiguration.colorCurves;
  40472. },
  40473. /**
  40474. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40475. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40476. * 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;
  40477. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40478. */
  40479. set: function (value) {
  40480. this._imageProcessingConfiguration.colorCurves = value;
  40481. },
  40482. enumerable: true,
  40483. configurable: true
  40484. });
  40485. StandardMaterial.prototype.getClassName = function () {
  40486. return "StandardMaterial";
  40487. };
  40488. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  40489. get: function () {
  40490. return this._useLogarithmicDepth;
  40491. },
  40492. set: function (value) {
  40493. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40494. this._markAllSubMeshesAsMiscDirty();
  40495. },
  40496. enumerable: true,
  40497. configurable: true
  40498. });
  40499. StandardMaterial.prototype.needAlphaBlending = function () {
  40500. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  40501. };
  40502. StandardMaterial.prototype.needAlphaTesting = function () {
  40503. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  40504. };
  40505. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  40506. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  40507. };
  40508. StandardMaterial.prototype.getAlphaTestTexture = function () {
  40509. return this._diffuseTexture;
  40510. };
  40511. /**
  40512. * Child classes can use it to update shaders
  40513. */
  40514. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40515. if (useInstances === void 0) { useInstances = false; }
  40516. if (subMesh.effect && this.isFrozen) {
  40517. if (this._wasPreviouslyReady && subMesh.effect) {
  40518. return true;
  40519. }
  40520. }
  40521. if (!subMesh._materialDefines) {
  40522. subMesh._materialDefines = new StandardMaterialDefines();
  40523. }
  40524. var scene = this.getScene();
  40525. var defines = subMesh._materialDefines;
  40526. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40527. if (defines._renderId === scene.getRenderId()) {
  40528. return true;
  40529. }
  40530. }
  40531. var engine = scene.getEngine();
  40532. // Lights
  40533. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40534. // Textures
  40535. if (defines._areTexturesDirty) {
  40536. defines._needUVs = false;
  40537. defines.MAINUV1 = false;
  40538. defines.MAINUV2 = false;
  40539. if (scene.texturesEnabled) {
  40540. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40541. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  40542. return false;
  40543. }
  40544. else {
  40545. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  40546. }
  40547. }
  40548. else {
  40549. defines.DIFFUSE = false;
  40550. }
  40551. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40552. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40553. return false;
  40554. }
  40555. else {
  40556. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40557. }
  40558. }
  40559. else {
  40560. defines.AMBIENT = false;
  40561. }
  40562. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40563. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40564. return false;
  40565. }
  40566. else {
  40567. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40568. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40569. }
  40570. }
  40571. else {
  40572. defines.OPACITY = false;
  40573. }
  40574. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40575. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  40576. return false;
  40577. }
  40578. else {
  40579. defines._needNormals = true;
  40580. defines.REFLECTION = true;
  40581. defines.ROUGHNESS = (this._roughness > 0);
  40582. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  40583. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  40584. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  40585. switch (this._reflectionTexture.coordinatesMode) {
  40586. case BABYLON.Texture.CUBIC_MODE:
  40587. case BABYLON.Texture.INVCUBIC_MODE:
  40588. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  40589. break;
  40590. case BABYLON.Texture.EXPLICIT_MODE:
  40591. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  40592. break;
  40593. case BABYLON.Texture.PLANAR_MODE:
  40594. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  40595. break;
  40596. case BABYLON.Texture.PROJECTION_MODE:
  40597. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  40598. break;
  40599. case BABYLON.Texture.SKYBOX_MODE:
  40600. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  40601. break;
  40602. case BABYLON.Texture.SPHERICAL_MODE:
  40603. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  40604. break;
  40605. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40606. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  40607. break;
  40608. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40609. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  40610. break;
  40611. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40612. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  40613. break;
  40614. }
  40615. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  40616. }
  40617. }
  40618. else {
  40619. defines.REFLECTION = false;
  40620. }
  40621. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40622. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40623. return false;
  40624. }
  40625. else {
  40626. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40627. }
  40628. }
  40629. else {
  40630. defines.EMISSIVE = false;
  40631. }
  40632. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40633. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40634. return false;
  40635. }
  40636. else {
  40637. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40638. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40639. }
  40640. }
  40641. else {
  40642. defines.LIGHTMAP = false;
  40643. }
  40644. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40645. if (!this._specularTexture.isReadyOrNotBlocking()) {
  40646. return false;
  40647. }
  40648. else {
  40649. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  40650. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  40651. }
  40652. }
  40653. else {
  40654. defines.SPECULAR = false;
  40655. }
  40656. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  40657. // Bump texure can not be not blocking.
  40658. if (!this._bumpTexture.isReady()) {
  40659. return false;
  40660. }
  40661. else {
  40662. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40663. defines.PARALLAX = this._useParallax;
  40664. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  40665. }
  40666. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40667. }
  40668. else {
  40669. defines.BUMP = false;
  40670. }
  40671. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40672. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  40673. return false;
  40674. }
  40675. else {
  40676. defines._needUVs = true;
  40677. defines.REFRACTION = true;
  40678. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  40679. }
  40680. }
  40681. else {
  40682. defines.REFRACTION = false;
  40683. }
  40684. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40685. }
  40686. else {
  40687. defines.DIFFUSE = false;
  40688. defines.AMBIENT = false;
  40689. defines.OPACITY = false;
  40690. defines.REFLECTION = false;
  40691. defines.EMISSIVE = false;
  40692. defines.LIGHTMAP = false;
  40693. defines.BUMP = false;
  40694. defines.REFRACTION = false;
  40695. }
  40696. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40697. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40698. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40699. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40700. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40701. }
  40702. if (defines._areImageProcessingDirty) {
  40703. if (!this._imageProcessingConfiguration.isReady()) {
  40704. return false;
  40705. }
  40706. this._imageProcessingConfiguration.prepareDefines(defines);
  40707. }
  40708. if (defines._areFresnelDirty) {
  40709. if (StandardMaterial.FresnelEnabled) {
  40710. // Fresnel
  40711. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40712. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40713. this._reflectionFresnelParameters) {
  40714. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40715. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40716. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40717. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40718. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40719. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40720. defines._needNormals = true;
  40721. defines.FRESNEL = true;
  40722. }
  40723. }
  40724. else {
  40725. defines.FRESNEL = false;
  40726. }
  40727. }
  40728. // Misc.
  40729. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  40730. // Attribs
  40731. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40732. // Values that need to be evaluated on every frame
  40733. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40734. // Get correct effect
  40735. if (defines.isDirty) {
  40736. defines.markAsProcessed();
  40737. scene.resetCachedMaterial();
  40738. // Fallbacks
  40739. var fallbacks = new BABYLON.EffectFallbacks();
  40740. if (defines.REFLECTION) {
  40741. fallbacks.addFallback(0, "REFLECTION");
  40742. }
  40743. if (defines.SPECULAR) {
  40744. fallbacks.addFallback(0, "SPECULAR");
  40745. }
  40746. if (defines.BUMP) {
  40747. fallbacks.addFallback(0, "BUMP");
  40748. }
  40749. if (defines.PARALLAX) {
  40750. fallbacks.addFallback(1, "PARALLAX");
  40751. }
  40752. if (defines.PARALLAXOCCLUSION) {
  40753. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40754. }
  40755. if (defines.SPECULAROVERALPHA) {
  40756. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40757. }
  40758. if (defines.FOG) {
  40759. fallbacks.addFallback(1, "FOG");
  40760. }
  40761. if (defines.POINTSIZE) {
  40762. fallbacks.addFallback(0, "POINTSIZE");
  40763. }
  40764. if (defines.LOGARITHMICDEPTH) {
  40765. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40766. }
  40767. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40768. if (defines.SPECULARTERM) {
  40769. fallbacks.addFallback(0, "SPECULARTERM");
  40770. }
  40771. if (defines.DIFFUSEFRESNEL) {
  40772. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40773. }
  40774. if (defines.OPACITYFRESNEL) {
  40775. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40776. }
  40777. if (defines.REFLECTIONFRESNEL) {
  40778. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40779. }
  40780. if (defines.EMISSIVEFRESNEL) {
  40781. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40782. }
  40783. if (defines.FRESNEL) {
  40784. fallbacks.addFallback(4, "FRESNEL");
  40785. }
  40786. //Attributes
  40787. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40788. if (defines.NORMAL) {
  40789. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40790. }
  40791. if (defines.UV1) {
  40792. attribs.push(BABYLON.VertexBuffer.UVKind);
  40793. }
  40794. if (defines.UV2) {
  40795. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40796. }
  40797. if (defines.VERTEXCOLOR) {
  40798. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40799. }
  40800. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40801. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40802. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40803. var shaderName = "default";
  40804. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40805. "vFogInfos", "vFogColor", "pointSize",
  40806. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40807. "mBones",
  40808. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40809. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40810. "vReflectionPosition", "vReflectionSize",
  40811. "logarithmicDepthConstant", "vTangentSpaceParams"
  40812. ];
  40813. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40814. var uniformBuffers = ["Material", "Scene"];
  40815. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40816. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40817. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40818. uniformsNames: uniforms,
  40819. uniformBuffersNames: uniformBuffers,
  40820. samplers: samplers,
  40821. defines: defines,
  40822. maxSimultaneousLights: this._maxSimultaneousLights
  40823. });
  40824. if (this.customShaderNameResolve) {
  40825. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40826. }
  40827. var join = defines.toString();
  40828. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40829. attributes: attribs,
  40830. uniformsNames: uniforms,
  40831. uniformBuffersNames: uniformBuffers,
  40832. samplers: samplers,
  40833. defines: join,
  40834. fallbacks: fallbacks,
  40835. onCompiled: this.onCompiled,
  40836. onError: this.onError,
  40837. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40838. }, engine), defines);
  40839. this.buildUniformLayout();
  40840. }
  40841. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40842. return false;
  40843. }
  40844. defines._renderId = scene.getRenderId();
  40845. this._wasPreviouslyReady = true;
  40846. return true;
  40847. };
  40848. StandardMaterial.prototype.buildUniformLayout = function () {
  40849. // Order is important !
  40850. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40851. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40852. this._uniformBuffer.addUniform("opacityParts", 4);
  40853. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40854. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40855. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40856. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40857. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40858. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40859. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40860. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40861. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40862. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40863. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40864. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40865. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40866. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40867. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40868. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40869. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40870. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40871. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40872. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40873. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40874. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40875. this._uniformBuffer.addUniform("specularMatrix", 16);
  40876. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40877. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40878. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40879. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40880. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40881. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40882. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40883. this._uniformBuffer.addUniform("pointSize", 1);
  40884. this._uniformBuffer.create();
  40885. };
  40886. StandardMaterial.prototype.unbind = function () {
  40887. if (this._activeEffect) {
  40888. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40889. this._activeEffect.setTexture("reflection2DSampler", null);
  40890. }
  40891. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40892. this._activeEffect.setTexture("refraction2DSampler", null);
  40893. }
  40894. }
  40895. _super.prototype.unbind.call(this);
  40896. };
  40897. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40898. var scene = this.getScene();
  40899. var defines = subMesh._materialDefines;
  40900. if (!defines) {
  40901. return;
  40902. }
  40903. var effect = subMesh.effect;
  40904. if (!effect) {
  40905. return;
  40906. }
  40907. this._activeEffect = effect;
  40908. // Matrices
  40909. this.bindOnlyWorldMatrix(world);
  40910. // Normal Matrix
  40911. if (defines.OBJECTSPACE_NORMALMAP) {
  40912. world.toNormalMatrix(this._normalMatrix);
  40913. this.bindOnlyNormalMatrix(this._normalMatrix);
  40914. }
  40915. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40916. // Bones
  40917. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40918. if (mustRebind) {
  40919. this._uniformBuffer.bindToEffect(effect, "Material");
  40920. this.bindViewProjection(effect);
  40921. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40922. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40923. // Fresnel
  40924. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40925. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40926. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40927. }
  40928. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40929. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40930. }
  40931. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40932. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40933. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40934. }
  40935. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40936. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40937. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40938. }
  40939. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40940. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40941. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40942. }
  40943. }
  40944. // Textures
  40945. if (scene.texturesEnabled) {
  40946. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40947. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40948. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40949. }
  40950. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40951. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40952. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40953. }
  40954. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40955. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40956. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40957. }
  40958. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40959. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40960. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40961. if (this._reflectionTexture.boundingBoxSize) {
  40962. var cubeTexture = this._reflectionTexture;
  40963. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40964. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40965. }
  40966. }
  40967. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40968. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40969. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40970. }
  40971. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40972. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40973. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40974. }
  40975. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40976. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40977. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40978. }
  40979. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40980. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40981. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40982. if (scene._mirroredCameraPosition) {
  40983. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40984. }
  40985. else {
  40986. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40987. }
  40988. }
  40989. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40990. var depth = 1.0;
  40991. if (!this._refractionTexture.isCube) {
  40992. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40993. if (this._refractionTexture.depth) {
  40994. depth = this._refractionTexture.depth;
  40995. }
  40996. }
  40997. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40998. }
  40999. }
  41000. // Point size
  41001. if (this.pointsCloud) {
  41002. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41003. }
  41004. if (defines.SPECULARTERM) {
  41005. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  41006. }
  41007. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  41008. // Diffuse
  41009. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  41010. }
  41011. // Textures
  41012. if (scene.texturesEnabled) {
  41013. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41014. effect.setTexture("diffuseSampler", this._diffuseTexture);
  41015. }
  41016. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41017. effect.setTexture("ambientSampler", this._ambientTexture);
  41018. }
  41019. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41020. effect.setTexture("opacitySampler", this._opacityTexture);
  41021. }
  41022. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41023. if (this._reflectionTexture.isCube) {
  41024. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  41025. }
  41026. else {
  41027. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  41028. }
  41029. }
  41030. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41031. effect.setTexture("emissiveSampler", this._emissiveTexture);
  41032. }
  41033. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41034. effect.setTexture("lightmapSampler", this._lightmapTexture);
  41035. }
  41036. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41037. effect.setTexture("specularSampler", this._specularTexture);
  41038. }
  41039. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41040. effect.setTexture("bumpSampler", this._bumpTexture);
  41041. }
  41042. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41043. var depth = 1.0;
  41044. if (this._refractionTexture.isCube) {
  41045. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  41046. }
  41047. else {
  41048. effect.setTexture("refraction2DSampler", this._refractionTexture);
  41049. }
  41050. }
  41051. }
  41052. // Clip plane
  41053. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  41054. // Colors
  41055. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  41056. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  41057. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41058. }
  41059. if (mustRebind || !this.isFrozen) {
  41060. // Lights
  41061. if (scene.lightsEnabled && !this._disableLighting) {
  41062. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  41063. }
  41064. // View
  41065. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  41066. this.bindView(effect);
  41067. }
  41068. // Fog
  41069. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  41070. // Morph targets
  41071. if (defines.NUM_MORPH_INFLUENCERS) {
  41072. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  41073. }
  41074. // Log. depth
  41075. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  41076. // image processing
  41077. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  41078. this._imageProcessingConfiguration.bind(this._activeEffect);
  41079. }
  41080. }
  41081. this._uniformBuffer.update();
  41082. this._afterBind(mesh, this._activeEffect);
  41083. };
  41084. StandardMaterial.prototype.getAnimatables = function () {
  41085. var results = [];
  41086. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  41087. results.push(this._diffuseTexture);
  41088. }
  41089. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41090. results.push(this._ambientTexture);
  41091. }
  41092. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41093. results.push(this._opacityTexture);
  41094. }
  41095. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41096. results.push(this._reflectionTexture);
  41097. }
  41098. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41099. results.push(this._emissiveTexture);
  41100. }
  41101. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  41102. results.push(this._specularTexture);
  41103. }
  41104. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41105. results.push(this._bumpTexture);
  41106. }
  41107. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41108. results.push(this._lightmapTexture);
  41109. }
  41110. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41111. results.push(this._refractionTexture);
  41112. }
  41113. return results;
  41114. };
  41115. StandardMaterial.prototype.getActiveTextures = function () {
  41116. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41117. if (this._diffuseTexture) {
  41118. activeTextures.push(this._diffuseTexture);
  41119. }
  41120. if (this._ambientTexture) {
  41121. activeTextures.push(this._ambientTexture);
  41122. }
  41123. if (this._opacityTexture) {
  41124. activeTextures.push(this._opacityTexture);
  41125. }
  41126. if (this._reflectionTexture) {
  41127. activeTextures.push(this._reflectionTexture);
  41128. }
  41129. if (this._emissiveTexture) {
  41130. activeTextures.push(this._emissiveTexture);
  41131. }
  41132. if (this._specularTexture) {
  41133. activeTextures.push(this._specularTexture);
  41134. }
  41135. if (this._bumpTexture) {
  41136. activeTextures.push(this._bumpTexture);
  41137. }
  41138. if (this._lightmapTexture) {
  41139. activeTextures.push(this._lightmapTexture);
  41140. }
  41141. if (this._refractionTexture) {
  41142. activeTextures.push(this._refractionTexture);
  41143. }
  41144. return activeTextures;
  41145. };
  41146. StandardMaterial.prototype.hasTexture = function (texture) {
  41147. if (_super.prototype.hasTexture.call(this, texture)) {
  41148. return true;
  41149. }
  41150. if (this._diffuseTexture === texture) {
  41151. return true;
  41152. }
  41153. if (this._ambientTexture === texture) {
  41154. return true;
  41155. }
  41156. if (this._opacityTexture === texture) {
  41157. return true;
  41158. }
  41159. if (this._reflectionTexture === texture) {
  41160. return true;
  41161. }
  41162. if (this._emissiveTexture === texture) {
  41163. return true;
  41164. }
  41165. if (this._specularTexture === texture) {
  41166. return true;
  41167. }
  41168. if (this._bumpTexture === texture) {
  41169. return true;
  41170. }
  41171. if (this._lightmapTexture === texture) {
  41172. return true;
  41173. }
  41174. if (this._refractionTexture === texture) {
  41175. return true;
  41176. }
  41177. return false;
  41178. };
  41179. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41180. if (forceDisposeTextures) {
  41181. if (this._diffuseTexture) {
  41182. this._diffuseTexture.dispose();
  41183. }
  41184. if (this._ambientTexture) {
  41185. this._ambientTexture.dispose();
  41186. }
  41187. if (this._opacityTexture) {
  41188. this._opacityTexture.dispose();
  41189. }
  41190. if (this._reflectionTexture) {
  41191. this._reflectionTexture.dispose();
  41192. }
  41193. if (this._emissiveTexture) {
  41194. this._emissiveTexture.dispose();
  41195. }
  41196. if (this._specularTexture) {
  41197. this._specularTexture.dispose();
  41198. }
  41199. if (this._bumpTexture) {
  41200. this._bumpTexture.dispose();
  41201. }
  41202. if (this._lightmapTexture) {
  41203. this._lightmapTexture.dispose();
  41204. }
  41205. if (this._refractionTexture) {
  41206. this._refractionTexture.dispose();
  41207. }
  41208. }
  41209. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41210. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41211. }
  41212. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41213. };
  41214. StandardMaterial.prototype.clone = function (name) {
  41215. var _this = this;
  41216. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  41217. result.name = name;
  41218. result.id = name;
  41219. return result;
  41220. };
  41221. StandardMaterial.prototype.serialize = function () {
  41222. return BABYLON.SerializationHelper.Serialize(this);
  41223. };
  41224. // Statics
  41225. StandardMaterial.Parse = function (source, scene, rootUrl) {
  41226. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  41227. };
  41228. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  41229. get: function () {
  41230. return StandardMaterial._DiffuseTextureEnabled;
  41231. },
  41232. set: function (value) {
  41233. if (StandardMaterial._DiffuseTextureEnabled === value) {
  41234. return;
  41235. }
  41236. StandardMaterial._DiffuseTextureEnabled = value;
  41237. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41238. },
  41239. enumerable: true,
  41240. configurable: true
  41241. });
  41242. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  41243. get: function () {
  41244. return StandardMaterial._AmbientTextureEnabled;
  41245. },
  41246. set: function (value) {
  41247. if (StandardMaterial._AmbientTextureEnabled === value) {
  41248. return;
  41249. }
  41250. StandardMaterial._AmbientTextureEnabled = value;
  41251. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41252. },
  41253. enumerable: true,
  41254. configurable: true
  41255. });
  41256. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  41257. get: function () {
  41258. return StandardMaterial._OpacityTextureEnabled;
  41259. },
  41260. set: function (value) {
  41261. if (StandardMaterial._OpacityTextureEnabled === value) {
  41262. return;
  41263. }
  41264. StandardMaterial._OpacityTextureEnabled = value;
  41265. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41266. },
  41267. enumerable: true,
  41268. configurable: true
  41269. });
  41270. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  41271. get: function () {
  41272. return StandardMaterial._ReflectionTextureEnabled;
  41273. },
  41274. set: function (value) {
  41275. if (StandardMaterial._ReflectionTextureEnabled === value) {
  41276. return;
  41277. }
  41278. StandardMaterial._ReflectionTextureEnabled = value;
  41279. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41280. },
  41281. enumerable: true,
  41282. configurable: true
  41283. });
  41284. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  41285. get: function () {
  41286. return StandardMaterial._EmissiveTextureEnabled;
  41287. },
  41288. set: function (value) {
  41289. if (StandardMaterial._EmissiveTextureEnabled === value) {
  41290. return;
  41291. }
  41292. StandardMaterial._EmissiveTextureEnabled = value;
  41293. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41294. },
  41295. enumerable: true,
  41296. configurable: true
  41297. });
  41298. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  41299. get: function () {
  41300. return StandardMaterial._SpecularTextureEnabled;
  41301. },
  41302. set: function (value) {
  41303. if (StandardMaterial._SpecularTextureEnabled === value) {
  41304. return;
  41305. }
  41306. StandardMaterial._SpecularTextureEnabled = value;
  41307. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41308. },
  41309. enumerable: true,
  41310. configurable: true
  41311. });
  41312. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  41313. get: function () {
  41314. return StandardMaterial._BumpTextureEnabled;
  41315. },
  41316. set: function (value) {
  41317. if (StandardMaterial._BumpTextureEnabled === value) {
  41318. return;
  41319. }
  41320. StandardMaterial._BumpTextureEnabled = value;
  41321. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  41327. get: function () {
  41328. return StandardMaterial._LightmapTextureEnabled;
  41329. },
  41330. set: function (value) {
  41331. if (StandardMaterial._LightmapTextureEnabled === value) {
  41332. return;
  41333. }
  41334. StandardMaterial._LightmapTextureEnabled = value;
  41335. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41336. },
  41337. enumerable: true,
  41338. configurable: true
  41339. });
  41340. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  41341. get: function () {
  41342. return StandardMaterial._RefractionTextureEnabled;
  41343. },
  41344. set: function (value) {
  41345. if (StandardMaterial._RefractionTextureEnabled === value) {
  41346. return;
  41347. }
  41348. StandardMaterial._RefractionTextureEnabled = value;
  41349. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41350. },
  41351. enumerable: true,
  41352. configurable: true
  41353. });
  41354. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  41355. get: function () {
  41356. return StandardMaterial._ColorGradingTextureEnabled;
  41357. },
  41358. set: function (value) {
  41359. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  41360. return;
  41361. }
  41362. StandardMaterial._ColorGradingTextureEnabled = value;
  41363. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41364. },
  41365. enumerable: true,
  41366. configurable: true
  41367. });
  41368. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  41369. get: function () {
  41370. return StandardMaterial._FresnelEnabled;
  41371. },
  41372. set: function (value) {
  41373. if (StandardMaterial._FresnelEnabled === value) {
  41374. return;
  41375. }
  41376. StandardMaterial._FresnelEnabled = value;
  41377. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  41378. },
  41379. enumerable: true,
  41380. configurable: true
  41381. });
  41382. // Flags used to enable or disable a type of texture for all Standard Materials
  41383. StandardMaterial._DiffuseTextureEnabled = true;
  41384. StandardMaterial._AmbientTextureEnabled = true;
  41385. StandardMaterial._OpacityTextureEnabled = true;
  41386. StandardMaterial._ReflectionTextureEnabled = true;
  41387. StandardMaterial._EmissiveTextureEnabled = true;
  41388. StandardMaterial._SpecularTextureEnabled = true;
  41389. StandardMaterial._BumpTextureEnabled = true;
  41390. StandardMaterial._LightmapTextureEnabled = true;
  41391. StandardMaterial._RefractionTextureEnabled = true;
  41392. StandardMaterial._ColorGradingTextureEnabled = true;
  41393. StandardMaterial._FresnelEnabled = true;
  41394. __decorate([
  41395. BABYLON.serializeAsTexture("diffuseTexture")
  41396. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  41397. __decorate([
  41398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41399. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  41400. __decorate([
  41401. BABYLON.serializeAsTexture("ambientTexture")
  41402. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  41403. __decorate([
  41404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41405. ], StandardMaterial.prototype, "ambientTexture", void 0);
  41406. __decorate([
  41407. BABYLON.serializeAsTexture("opacityTexture")
  41408. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  41409. __decorate([
  41410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41411. ], StandardMaterial.prototype, "opacityTexture", void 0);
  41412. __decorate([
  41413. BABYLON.serializeAsTexture("reflectionTexture")
  41414. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  41415. __decorate([
  41416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41417. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  41418. __decorate([
  41419. BABYLON.serializeAsTexture("emissiveTexture")
  41420. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  41421. __decorate([
  41422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41423. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  41424. __decorate([
  41425. BABYLON.serializeAsTexture("specularTexture")
  41426. ], StandardMaterial.prototype, "_specularTexture", void 0);
  41427. __decorate([
  41428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41429. ], StandardMaterial.prototype, "specularTexture", void 0);
  41430. __decorate([
  41431. BABYLON.serializeAsTexture("bumpTexture")
  41432. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  41433. __decorate([
  41434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41435. ], StandardMaterial.prototype, "bumpTexture", void 0);
  41436. __decorate([
  41437. BABYLON.serializeAsTexture("lightmapTexture")
  41438. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  41439. __decorate([
  41440. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41441. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  41442. __decorate([
  41443. BABYLON.serializeAsTexture("refractionTexture")
  41444. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  41445. __decorate([
  41446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41447. ], StandardMaterial.prototype, "refractionTexture", void 0);
  41448. __decorate([
  41449. BABYLON.serializeAsColor3("ambient")
  41450. ], StandardMaterial.prototype, "ambientColor", void 0);
  41451. __decorate([
  41452. BABYLON.serializeAsColor3("diffuse")
  41453. ], StandardMaterial.prototype, "diffuseColor", void 0);
  41454. __decorate([
  41455. BABYLON.serializeAsColor3("specular")
  41456. ], StandardMaterial.prototype, "specularColor", void 0);
  41457. __decorate([
  41458. BABYLON.serializeAsColor3("emissive")
  41459. ], StandardMaterial.prototype, "emissiveColor", void 0);
  41460. __decorate([
  41461. BABYLON.serialize()
  41462. ], StandardMaterial.prototype, "specularPower", void 0);
  41463. __decorate([
  41464. BABYLON.serialize("useAlphaFromDiffuseTexture")
  41465. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  41466. __decorate([
  41467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41468. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  41469. __decorate([
  41470. BABYLON.serialize("useEmissiveAsIllumination")
  41471. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  41472. __decorate([
  41473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41474. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  41475. __decorate([
  41476. BABYLON.serialize("linkEmissiveWithDiffuse")
  41477. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  41478. __decorate([
  41479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41480. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  41481. __decorate([
  41482. BABYLON.serialize("useSpecularOverAlpha")
  41483. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  41484. __decorate([
  41485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41486. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  41487. __decorate([
  41488. BABYLON.serialize("useReflectionOverAlpha")
  41489. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  41490. __decorate([
  41491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41492. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  41493. __decorate([
  41494. BABYLON.serialize("disableLighting")
  41495. ], StandardMaterial.prototype, "_disableLighting", void 0);
  41496. __decorate([
  41497. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41498. ], StandardMaterial.prototype, "disableLighting", void 0);
  41499. __decorate([
  41500. BABYLON.serialize("useObjectSpaceNormalMap")
  41501. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  41502. __decorate([
  41503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41504. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  41505. __decorate([
  41506. BABYLON.serialize("useParallax")
  41507. ], StandardMaterial.prototype, "_useParallax", void 0);
  41508. __decorate([
  41509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41510. ], StandardMaterial.prototype, "useParallax", void 0);
  41511. __decorate([
  41512. BABYLON.serialize("useParallaxOcclusion")
  41513. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  41514. __decorate([
  41515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41516. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  41517. __decorate([
  41518. BABYLON.serialize()
  41519. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  41520. __decorate([
  41521. BABYLON.serialize("roughness")
  41522. ], StandardMaterial.prototype, "_roughness", void 0);
  41523. __decorate([
  41524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41525. ], StandardMaterial.prototype, "roughness", void 0);
  41526. __decorate([
  41527. BABYLON.serialize()
  41528. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  41529. __decorate([
  41530. BABYLON.serialize()
  41531. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  41532. __decorate([
  41533. BABYLON.serialize("useLightmapAsShadowmap")
  41534. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  41535. __decorate([
  41536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41537. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41538. __decorate([
  41539. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  41540. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  41541. __decorate([
  41542. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41543. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  41544. __decorate([
  41545. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  41546. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  41547. __decorate([
  41548. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  41549. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  41550. __decorate([
  41551. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  41552. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  41553. __decorate([
  41554. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41555. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  41556. __decorate([
  41557. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  41558. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  41559. __decorate([
  41560. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41561. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  41562. __decorate([
  41563. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  41564. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  41565. __decorate([
  41566. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41567. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  41568. __decorate([
  41569. BABYLON.serialize("useReflectionFresnelFromSpecular")
  41570. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  41571. __decorate([
  41572. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41573. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  41574. __decorate([
  41575. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  41576. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  41577. __decorate([
  41578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41579. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  41580. __decorate([
  41581. BABYLON.serialize("maxSimultaneousLights")
  41582. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  41583. __decorate([
  41584. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41585. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  41586. __decorate([
  41587. BABYLON.serialize("invertNormalMapX")
  41588. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  41589. __decorate([
  41590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41591. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  41592. __decorate([
  41593. BABYLON.serialize("invertNormalMapY")
  41594. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  41595. __decorate([
  41596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41597. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  41598. __decorate([
  41599. BABYLON.serialize("twoSidedLighting")
  41600. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  41601. __decorate([
  41602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41603. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  41604. __decorate([
  41605. BABYLON.serialize()
  41606. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  41607. return StandardMaterial;
  41608. }(BABYLON.PushMaterial));
  41609. BABYLON.StandardMaterial = StandardMaterial;
  41610. })(BABYLON || (BABYLON = {}));
  41611. //# sourceMappingURL=babylon.standardMaterial.js.map
  41612. "use strict";
  41613. var BABYLON;
  41614. (function (BABYLON) {
  41615. /**
  41616. * Manages the defines for the PBR Material.
  41617. */
  41618. var PBRMaterialDefines = /** @class */ (function (_super) {
  41619. __extends(PBRMaterialDefines, _super);
  41620. /**
  41621. * Initializes the PBR Material defines.
  41622. */
  41623. function PBRMaterialDefines() {
  41624. var _this = _super.call(this) || this;
  41625. _this.PBR = true;
  41626. _this.MAINUV1 = false;
  41627. _this.MAINUV2 = false;
  41628. _this.UV1 = false;
  41629. _this.UV2 = false;
  41630. _this.ALBEDO = false;
  41631. _this.ALBEDODIRECTUV = 0;
  41632. _this.VERTEXCOLOR = false;
  41633. _this.AMBIENT = false;
  41634. _this.AMBIENTDIRECTUV = 0;
  41635. _this.AMBIENTINGRAYSCALE = false;
  41636. _this.OPACITY = false;
  41637. _this.VERTEXALPHA = false;
  41638. _this.OPACITYDIRECTUV = 0;
  41639. _this.OPACITYRGB = false;
  41640. _this.ALPHATEST = false;
  41641. _this.DEPTHPREPASS = false;
  41642. _this.ALPHABLEND = false;
  41643. _this.ALPHAFROMALBEDO = false;
  41644. _this.ALPHATESTVALUE = "0.5";
  41645. _this.SPECULAROVERALPHA = false;
  41646. _this.RADIANCEOVERALPHA = false;
  41647. _this.ALPHAFRESNEL = false;
  41648. _this.LINEARALPHAFRESNEL = false;
  41649. _this.PREMULTIPLYALPHA = false;
  41650. _this.EMISSIVE = false;
  41651. _this.EMISSIVEDIRECTUV = 0;
  41652. _this.REFLECTIVITY = false;
  41653. _this.REFLECTIVITYDIRECTUV = 0;
  41654. _this.SPECULARTERM = false;
  41655. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  41656. _this.MICROSURFACEAUTOMATIC = false;
  41657. _this.LODBASEDMICROSFURACE = false;
  41658. _this.MICROSURFACEMAP = false;
  41659. _this.MICROSURFACEMAPDIRECTUV = 0;
  41660. _this.METALLICWORKFLOW = false;
  41661. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  41662. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  41663. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  41664. _this.AOSTOREINMETALMAPRED = false;
  41665. _this.ENVIRONMENTBRDF = false;
  41666. _this.NORMAL = false;
  41667. _this.TANGENT = false;
  41668. _this.BUMP = false;
  41669. _this.BUMPDIRECTUV = 0;
  41670. _this.OBJECTSPACE_NORMALMAP = false;
  41671. _this.PARALLAX = false;
  41672. _this.PARALLAXOCCLUSION = false;
  41673. _this.NORMALXYSCALE = true;
  41674. _this.LIGHTMAP = false;
  41675. _this.LIGHTMAPDIRECTUV = 0;
  41676. _this.USELIGHTMAPASSHADOWMAP = false;
  41677. _this.GAMMALIGHTMAP = false;
  41678. _this.REFLECTION = false;
  41679. _this.REFLECTIONMAP_3D = false;
  41680. _this.REFLECTIONMAP_SPHERICAL = false;
  41681. _this.REFLECTIONMAP_PLANAR = false;
  41682. _this.REFLECTIONMAP_CUBIC = false;
  41683. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41684. _this.REFLECTIONMAP_PROJECTION = false;
  41685. _this.REFLECTIONMAP_SKYBOX = false;
  41686. _this.REFLECTIONMAP_EXPLICIT = false;
  41687. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41688. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41689. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41690. _this.INVERTCUBICMAP = false;
  41691. _this.USESPHERICALFROMREFLECTIONMAP = false;
  41692. _this.USESPHERICALINVERTEX = false;
  41693. _this.REFLECTIONMAP_OPPOSITEZ = false;
  41694. _this.LODINREFLECTIONALPHA = false;
  41695. _this.GAMMAREFLECTION = false;
  41696. _this.RADIANCEOCCLUSION = false;
  41697. _this.HORIZONOCCLUSION = false;
  41698. _this.REFRACTION = false;
  41699. _this.REFRACTIONMAP_3D = false;
  41700. _this.REFRACTIONMAP_OPPOSITEZ = false;
  41701. _this.LODINREFRACTIONALPHA = false;
  41702. _this.GAMMAREFRACTION = false;
  41703. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  41704. _this.INSTANCES = false;
  41705. _this.NUM_BONE_INFLUENCERS = 0;
  41706. _this.BonesPerMesh = 0;
  41707. _this.NONUNIFORMSCALING = false;
  41708. _this.MORPHTARGETS = false;
  41709. _this.MORPHTARGETS_NORMAL = false;
  41710. _this.MORPHTARGETS_TANGENT = false;
  41711. _this.NUM_MORPH_INFLUENCERS = 0;
  41712. _this.IMAGEPROCESSING = false;
  41713. _this.VIGNETTE = false;
  41714. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41715. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41716. _this.TONEMAPPING = false;
  41717. _this.CONTRAST = false;
  41718. _this.COLORCURVES = false;
  41719. _this.COLORGRADING = false;
  41720. _this.COLORGRADING3D = false;
  41721. _this.SAMPLER3DGREENDEPTH = false;
  41722. _this.SAMPLER3DBGRMAP = false;
  41723. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41724. _this.EXPOSURE = false;
  41725. _this.USEPHYSICALLIGHTFALLOFF = false;
  41726. _this.TWOSIDEDLIGHTING = false;
  41727. _this.SHADOWFLOAT = false;
  41728. _this.CLIPPLANE = false;
  41729. _this.POINTSIZE = false;
  41730. _this.FOG = false;
  41731. _this.LOGARITHMICDEPTH = false;
  41732. _this.FORCENORMALFORWARD = false;
  41733. _this.UNLIT = false;
  41734. _this.rebuild();
  41735. return _this;
  41736. }
  41737. /**
  41738. * Resets the PBR Material defines.
  41739. */
  41740. PBRMaterialDefines.prototype.reset = function () {
  41741. _super.prototype.reset.call(this);
  41742. this.ALPHATESTVALUE = "0.5";
  41743. this.PBR = true;
  41744. };
  41745. return PBRMaterialDefines;
  41746. }(BABYLON.MaterialDefines));
  41747. /**
  41748. * The Physically based material base class of BJS.
  41749. *
  41750. * This offers the main features of a standard PBR material.
  41751. * For more information, please refer to the documentation :
  41752. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41753. */
  41754. var PBRBaseMaterial = /** @class */ (function (_super) {
  41755. __extends(PBRBaseMaterial, _super);
  41756. /**
  41757. * Instantiates a new PBRMaterial instance.
  41758. *
  41759. * @param name The material name
  41760. * @param scene The scene the material will be use in.
  41761. */
  41762. function PBRBaseMaterial(name, scene) {
  41763. var _this = _super.call(this, name, scene) || this;
  41764. /**
  41765. * Intensity of the direct lights e.g. the four lights available in your scene.
  41766. * This impacts both the direct diffuse and specular highlights.
  41767. */
  41768. _this._directIntensity = 1.0;
  41769. /**
  41770. * Intensity of the emissive part of the material.
  41771. * This helps controlling the emissive effect without modifying the emissive color.
  41772. */
  41773. _this._emissiveIntensity = 1.0;
  41774. /**
  41775. * Intensity of the environment e.g. how much the environment will light the object
  41776. * either through harmonics for rough material or through the refelction for shiny ones.
  41777. */
  41778. _this._environmentIntensity = 1.0;
  41779. /**
  41780. * This is a special control allowing the reduction of the specular highlights coming from the
  41781. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41782. */
  41783. _this._specularIntensity = 1.0;
  41784. /**
  41785. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41786. */
  41787. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41788. /**
  41789. * Debug Control allowing disabling the bump map on this material.
  41790. */
  41791. _this._disableBumpMap = false;
  41792. /**
  41793. * AKA Occlusion Texture Intensity in other nomenclature.
  41794. */
  41795. _this._ambientTextureStrength = 1.0;
  41796. /**
  41797. * The color of a material in ambient lighting.
  41798. */
  41799. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41800. /**
  41801. * AKA Diffuse Color in other nomenclature.
  41802. */
  41803. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41804. /**
  41805. * AKA Specular Color in other nomenclature.
  41806. */
  41807. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41808. /**
  41809. * The color applied when light is reflected from a material.
  41810. */
  41811. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41812. /**
  41813. * The color applied when light is emitted from a material.
  41814. */
  41815. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41816. /**
  41817. * AKA Glossiness in other nomenclature.
  41818. */
  41819. _this._microSurface = 0.9;
  41820. /**
  41821. * source material index of refraction (IOR)' / 'destination material IOR.
  41822. */
  41823. _this._indexOfRefraction = 0.66;
  41824. /**
  41825. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41826. */
  41827. _this._invertRefractionY = false;
  41828. /**
  41829. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41830. * Materials half opaque for instance using refraction could benefit from this control.
  41831. */
  41832. _this._linkRefractionWithTransparency = false;
  41833. /**
  41834. * Specifies that the material will use the light map as a show map.
  41835. */
  41836. _this._useLightmapAsShadowmap = false;
  41837. /**
  41838. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41839. * makes the reflect vector face the model (under horizon).
  41840. */
  41841. _this._useHorizonOcclusion = true;
  41842. /**
  41843. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41844. * too much the area relying on ambient texture to define their ambient occlusion.
  41845. */
  41846. _this._useRadianceOcclusion = true;
  41847. /**
  41848. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41849. */
  41850. _this._useAlphaFromAlbedoTexture = false;
  41851. /**
  41852. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41853. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41854. */
  41855. _this._useSpecularOverAlpha = true;
  41856. /**
  41857. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41858. */
  41859. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41860. /**
  41861. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41862. */
  41863. _this._useRoughnessFromMetallicTextureAlpha = true;
  41864. /**
  41865. * Specifies if the metallic texture contains the roughness information in its green channel.
  41866. */
  41867. _this._useRoughnessFromMetallicTextureGreen = false;
  41868. /**
  41869. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41870. */
  41871. _this._useMetallnessFromMetallicTextureBlue = false;
  41872. /**
  41873. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41874. */
  41875. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41876. /**
  41877. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41878. */
  41879. _this._useAmbientInGrayScale = false;
  41880. /**
  41881. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41882. * The material will try to infer what glossiness each pixel should be.
  41883. */
  41884. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41885. /**
  41886. * BJS is using an harcoded light falloff based on a manually sets up range.
  41887. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41888. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41889. */
  41890. _this._usePhysicalLightFalloff = true;
  41891. /**
  41892. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41893. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41894. */
  41895. _this._useRadianceOverAlpha = true;
  41896. /**
  41897. * Allows using an object space normal map (instead of tangent space).
  41898. */
  41899. _this._useObjectSpaceNormalMap = false;
  41900. /**
  41901. * Allows using the bump map in parallax mode.
  41902. */
  41903. _this._useParallax = false;
  41904. /**
  41905. * Allows using the bump map in parallax occlusion mode.
  41906. */
  41907. _this._useParallaxOcclusion = false;
  41908. /**
  41909. * Controls the scale bias of the parallax mode.
  41910. */
  41911. _this._parallaxScaleBias = 0.05;
  41912. /**
  41913. * If sets to true, disables all the lights affecting the material.
  41914. */
  41915. _this._disableLighting = false;
  41916. /**
  41917. * Number of Simultaneous lights allowed on the material.
  41918. */
  41919. _this._maxSimultaneousLights = 4;
  41920. /**
  41921. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41922. */
  41923. _this._invertNormalMapX = false;
  41924. /**
  41925. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41926. */
  41927. _this._invertNormalMapY = false;
  41928. /**
  41929. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41930. */
  41931. _this._twoSidedLighting = false;
  41932. /**
  41933. * Defines the alpha limits in alpha test mode.
  41934. */
  41935. _this._alphaCutOff = 0.4;
  41936. /**
  41937. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41938. */
  41939. _this._forceAlphaTest = false;
  41940. /**
  41941. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41942. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41943. */
  41944. _this._useAlphaFresnel = false;
  41945. /**
  41946. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41947. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41948. */
  41949. _this._useLinearAlphaFresnel = false;
  41950. /**
  41951. * The transparency mode of the material.
  41952. */
  41953. _this._transparencyMode = null;
  41954. /**
  41955. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41956. * from cos thetav and roughness:
  41957. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41958. */
  41959. _this._environmentBRDFTexture = null;
  41960. /**
  41961. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41962. */
  41963. _this._forceIrradianceInFragment = false;
  41964. /**
  41965. * Force normal to face away from face.
  41966. */
  41967. _this._forceNormalForward = false;
  41968. /**
  41969. * Stores the available render targets.
  41970. */
  41971. _this._renderTargets = new BABYLON.SmartArray(16);
  41972. /**
  41973. * Sets the global ambient color for the material used in lighting calculations.
  41974. */
  41975. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41976. /**
  41977. * If set to true, no lighting calculations will be applied.
  41978. */
  41979. _this._unlit = false;
  41980. // Setup the default processing configuration to the scene.
  41981. _this._attachImageProcessingConfiguration(null);
  41982. _this.getRenderTargetTextures = function () {
  41983. _this._renderTargets.reset();
  41984. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41985. _this._renderTargets.push(_this._reflectionTexture);
  41986. }
  41987. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41988. _this._renderTargets.push(_this._refractionTexture);
  41989. }
  41990. return _this._renderTargets;
  41991. };
  41992. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41993. return _this;
  41994. }
  41995. /**
  41996. * Attaches a new image processing configuration to the PBR Material.
  41997. * @param configuration
  41998. */
  41999. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42000. var _this = this;
  42001. if (configuration === this._imageProcessingConfiguration) {
  42002. return;
  42003. }
  42004. // Detaches observer.
  42005. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42006. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42007. }
  42008. // Pick the scene configuration if needed.
  42009. if (!configuration) {
  42010. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42011. }
  42012. else {
  42013. this._imageProcessingConfiguration = configuration;
  42014. }
  42015. // Attaches observer.
  42016. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42017. _this._markAllSubMeshesAsImageProcessingDirty();
  42018. });
  42019. };
  42020. /**
  42021. * Gets the name of the material class.
  42022. */
  42023. PBRBaseMaterial.prototype.getClassName = function () {
  42024. return "PBRBaseMaterial";
  42025. };
  42026. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  42027. /**
  42028. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  42029. */
  42030. get: function () {
  42031. return this._useLogarithmicDepth;
  42032. },
  42033. /**
  42034. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  42035. */
  42036. set: function (value) {
  42037. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42038. },
  42039. enumerable: true,
  42040. configurable: true
  42041. });
  42042. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  42043. /**
  42044. * Gets the current transparency mode.
  42045. */
  42046. get: function () {
  42047. return this._transparencyMode;
  42048. },
  42049. /**
  42050. * Sets the transparency mode of the material.
  42051. */
  42052. set: function (value) {
  42053. if (this._transparencyMode === value) {
  42054. return;
  42055. }
  42056. this._transparencyMode = value;
  42057. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  42058. this._markAllSubMeshesAsTexturesAndMiscDirty();
  42059. },
  42060. enumerable: true,
  42061. configurable: true
  42062. });
  42063. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  42064. /**
  42065. * Returns true if alpha blending should be disabled.
  42066. */
  42067. get: function () {
  42068. return (this._linkRefractionWithTransparency ||
  42069. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  42070. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  42071. },
  42072. enumerable: true,
  42073. configurable: true
  42074. });
  42075. /**
  42076. * Specifies whether or not this material should be rendered in alpha blend mode.
  42077. */
  42078. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  42079. if (this._disableAlphaBlending) {
  42080. return false;
  42081. }
  42082. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  42083. };
  42084. /**
  42085. * Specifies if the mesh will require alpha blending.
  42086. * @param mesh - BJS mesh.
  42087. */
  42088. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  42089. if (this._disableAlphaBlending) {
  42090. return false;
  42091. }
  42092. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  42093. };
  42094. /**
  42095. * Specifies whether or not this material should be rendered in alpha test mode.
  42096. */
  42097. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  42098. if (this._forceAlphaTest) {
  42099. return true;
  42100. }
  42101. if (this._linkRefractionWithTransparency) {
  42102. return false;
  42103. }
  42104. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  42105. };
  42106. /**
  42107. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  42108. */
  42109. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  42110. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  42111. };
  42112. /**
  42113. * Gets the texture used for the alpha test.
  42114. */
  42115. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  42116. return this._albedoTexture;
  42117. };
  42118. /**
  42119. * Specifies that the submesh is ready to be used.
  42120. * @param mesh - BJS mesh.
  42121. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  42122. * @param useInstances - Specifies that instances should be used.
  42123. * @returns - boolean indicating that the submesh is ready or not.
  42124. */
  42125. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42126. if (subMesh.effect && this.isFrozen) {
  42127. if (this._wasPreviouslyReady) {
  42128. return true;
  42129. }
  42130. }
  42131. if (!subMesh._materialDefines) {
  42132. subMesh._materialDefines = new PBRMaterialDefines();
  42133. }
  42134. var defines = subMesh._materialDefines;
  42135. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42136. if (defines._renderId === this.getScene().getRenderId()) {
  42137. return true;
  42138. }
  42139. }
  42140. var scene = this.getScene();
  42141. var engine = scene.getEngine();
  42142. if (defines._areTexturesDirty) {
  42143. if (scene.texturesEnabled) {
  42144. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42145. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  42146. return false;
  42147. }
  42148. }
  42149. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42150. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42151. return false;
  42152. }
  42153. }
  42154. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42155. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42156. return false;
  42157. }
  42158. }
  42159. var reflectionTexture = this._getReflectionTexture();
  42160. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42161. if (!reflectionTexture.isReadyOrNotBlocking()) {
  42162. return false;
  42163. }
  42164. }
  42165. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42166. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42167. return false;
  42168. }
  42169. }
  42170. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42171. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42172. return false;
  42173. }
  42174. }
  42175. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42176. if (this._metallicTexture) {
  42177. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  42178. return false;
  42179. }
  42180. }
  42181. else if (this._reflectivityTexture) {
  42182. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  42183. return false;
  42184. }
  42185. }
  42186. if (this._microSurfaceTexture) {
  42187. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  42188. return false;
  42189. }
  42190. }
  42191. }
  42192. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42193. // Bump texture cannot be not blocking.
  42194. if (!this._bumpTexture.isReady()) {
  42195. return false;
  42196. }
  42197. }
  42198. var refractionTexture = this._getRefractionTexture();
  42199. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42200. if (!refractionTexture.isReadyOrNotBlocking()) {
  42201. return false;
  42202. }
  42203. }
  42204. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42205. // This is blocking.
  42206. if (!this._environmentBRDFTexture.isReady()) {
  42207. return false;
  42208. }
  42209. }
  42210. }
  42211. }
  42212. if (defines._areImageProcessingDirty) {
  42213. if (!this._imageProcessingConfiguration.isReady()) {
  42214. return false;
  42215. }
  42216. }
  42217. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42218. mesh.createNormals(true);
  42219. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  42220. }
  42221. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  42222. if (effect) {
  42223. scene.resetCachedMaterial();
  42224. subMesh.setEffect(effect, defines);
  42225. this.buildUniformLayout();
  42226. }
  42227. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42228. return false;
  42229. }
  42230. defines._renderId = scene.getRenderId();
  42231. this._wasPreviouslyReady = true;
  42232. return true;
  42233. };
  42234. /**
  42235. * Specifies if the material uses metallic roughness workflow.
  42236. * @returns boolean specifiying if the material uses metallic roughness workflow.
  42237. */
  42238. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  42239. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  42240. return true;
  42241. }
  42242. return false;
  42243. };
  42244. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  42245. if (onCompiled === void 0) { onCompiled = null; }
  42246. if (onError === void 0) { onError = null; }
  42247. if (useInstances === void 0) { useInstances = null; }
  42248. if (useClipPlane === void 0) { useClipPlane = null; }
  42249. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  42250. if (!defines.isDirty) {
  42251. return null;
  42252. }
  42253. defines.markAsProcessed();
  42254. var scene = this.getScene();
  42255. var engine = scene.getEngine();
  42256. // Fallbacks
  42257. var fallbacks = new BABYLON.EffectFallbacks();
  42258. var fallbackRank = 0;
  42259. if (defines.USESPHERICALINVERTEX) {
  42260. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  42261. }
  42262. if (defines.FOG) {
  42263. fallbacks.addFallback(fallbackRank, "FOG");
  42264. }
  42265. if (defines.POINTSIZE) {
  42266. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  42267. }
  42268. if (defines.LOGARITHMICDEPTH) {
  42269. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  42270. }
  42271. if (defines.PARALLAX) {
  42272. fallbacks.addFallback(fallbackRank, "PARALLAX");
  42273. }
  42274. if (defines.PARALLAXOCCLUSION) {
  42275. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  42276. }
  42277. if (defines.ENVIRONMENTBRDF) {
  42278. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  42279. }
  42280. if (defines.TANGENT) {
  42281. fallbacks.addFallback(fallbackRank++, "TANGENT");
  42282. }
  42283. if (defines.BUMP) {
  42284. fallbacks.addFallback(fallbackRank++, "BUMP");
  42285. }
  42286. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  42287. if (defines.SPECULARTERM) {
  42288. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  42289. }
  42290. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  42291. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  42292. }
  42293. if (defines.LIGHTMAP) {
  42294. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  42295. }
  42296. if (defines.NORMAL) {
  42297. fallbacks.addFallback(fallbackRank++, "NORMAL");
  42298. }
  42299. if (defines.AMBIENT) {
  42300. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  42301. }
  42302. if (defines.EMISSIVE) {
  42303. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  42304. }
  42305. if (defines.VERTEXCOLOR) {
  42306. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  42307. }
  42308. if (defines.NUM_BONE_INFLUENCERS > 0) {
  42309. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  42310. }
  42311. if (defines.MORPHTARGETS) {
  42312. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  42313. }
  42314. //Attributes
  42315. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42316. if (defines.NORMAL) {
  42317. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42318. }
  42319. if (defines.TANGENT) {
  42320. attribs.push(BABYLON.VertexBuffer.TangentKind);
  42321. }
  42322. if (defines.UV1) {
  42323. attribs.push(BABYLON.VertexBuffer.UVKind);
  42324. }
  42325. if (defines.UV2) {
  42326. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42327. }
  42328. if (defines.VERTEXCOLOR) {
  42329. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42330. }
  42331. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42332. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42333. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42334. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  42335. "vFogInfos", "vFogColor", "pointSize",
  42336. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  42337. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42338. "mBones",
  42339. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  42340. "vLightingIntensity",
  42341. "logarithmicDepthConstant",
  42342. "vSphericalX", "vSphericalY", "vSphericalZ",
  42343. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  42344. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  42345. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  42346. "vTangentSpaceParams"
  42347. ];
  42348. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  42349. "bumpSampler", "lightmapSampler", "opacitySampler",
  42350. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  42351. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  42352. "microSurfaceSampler", "environmentBrdfSampler"];
  42353. var uniformBuffers = ["Material", "Scene"];
  42354. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42355. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42356. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42357. uniformsNames: uniforms,
  42358. uniformBuffersNames: uniformBuffers,
  42359. samplers: samplers,
  42360. defines: defines,
  42361. maxSimultaneousLights: this._maxSimultaneousLights
  42362. });
  42363. var join = defines.toString();
  42364. return engine.createEffect("pbr", {
  42365. attributes: attribs,
  42366. uniformsNames: uniforms,
  42367. uniformBuffersNames: uniformBuffers,
  42368. samplers: samplers,
  42369. defines: join,
  42370. fallbacks: fallbacks,
  42371. onCompiled: onCompiled,
  42372. onError: onError,
  42373. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42374. }, engine);
  42375. };
  42376. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  42377. if (useInstances === void 0) { useInstances = null; }
  42378. if (useClipPlane === void 0) { useClipPlane = null; }
  42379. var scene = this.getScene();
  42380. var engine = scene.getEngine();
  42381. // Lights
  42382. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42383. defines._needNormals = true;
  42384. // Textures
  42385. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  42386. if (defines._areTexturesDirty) {
  42387. defines._needUVs = false;
  42388. if (scene.texturesEnabled) {
  42389. if (scene.getEngine().getCaps().textureLOD) {
  42390. defines.LODBASEDMICROSFURACE = true;
  42391. }
  42392. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42393. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  42394. }
  42395. else {
  42396. defines.ALBEDO = false;
  42397. }
  42398. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42399. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42400. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  42401. }
  42402. else {
  42403. defines.AMBIENT = false;
  42404. }
  42405. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42406. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42407. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42408. }
  42409. else {
  42410. defines.OPACITY = false;
  42411. }
  42412. var reflectionTexture = this._getReflectionTexture();
  42413. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42414. defines.REFLECTION = true;
  42415. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  42416. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  42417. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  42418. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  42419. defines.INVERTCUBICMAP = true;
  42420. }
  42421. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  42422. switch (reflectionTexture.coordinatesMode) {
  42423. case BABYLON.Texture.CUBIC_MODE:
  42424. case BABYLON.Texture.INVCUBIC_MODE:
  42425. defines.REFLECTIONMAP_CUBIC = true;
  42426. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  42427. break;
  42428. case BABYLON.Texture.EXPLICIT_MODE:
  42429. defines.REFLECTIONMAP_EXPLICIT = true;
  42430. break;
  42431. case BABYLON.Texture.PLANAR_MODE:
  42432. defines.REFLECTIONMAP_PLANAR = true;
  42433. break;
  42434. case BABYLON.Texture.PROJECTION_MODE:
  42435. defines.REFLECTIONMAP_PROJECTION = true;
  42436. break;
  42437. case BABYLON.Texture.SKYBOX_MODE:
  42438. defines.REFLECTIONMAP_SKYBOX = true;
  42439. break;
  42440. case BABYLON.Texture.SPHERICAL_MODE:
  42441. defines.REFLECTIONMAP_SPHERICAL = true;
  42442. break;
  42443. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42444. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  42445. break;
  42446. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42447. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  42448. break;
  42449. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42450. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  42451. break;
  42452. }
  42453. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  42454. if (reflectionTexture.sphericalPolynomial) {
  42455. defines.USESPHERICALFROMREFLECTIONMAP = true;
  42456. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  42457. defines.USESPHERICALINVERTEX = false;
  42458. }
  42459. else {
  42460. defines.USESPHERICALINVERTEX = true;
  42461. }
  42462. }
  42463. }
  42464. }
  42465. else {
  42466. defines.REFLECTION = false;
  42467. defines.REFLECTIONMAP_3D = false;
  42468. defines.REFLECTIONMAP_SPHERICAL = false;
  42469. defines.REFLECTIONMAP_PLANAR = false;
  42470. defines.REFLECTIONMAP_CUBIC = false;
  42471. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42472. defines.REFLECTIONMAP_PROJECTION = false;
  42473. defines.REFLECTIONMAP_SKYBOX = false;
  42474. defines.REFLECTIONMAP_EXPLICIT = false;
  42475. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42476. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42477. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42478. defines.INVERTCUBICMAP = false;
  42479. defines.USESPHERICALFROMREFLECTIONMAP = false;
  42480. defines.USESPHERICALINVERTEX = false;
  42481. defines.REFLECTIONMAP_OPPOSITEZ = false;
  42482. defines.LODINREFLECTIONALPHA = false;
  42483. defines.GAMMAREFLECTION = false;
  42484. }
  42485. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42486. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42487. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42488. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  42489. }
  42490. else {
  42491. defines.LIGHTMAP = false;
  42492. }
  42493. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42494. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42495. }
  42496. else {
  42497. defines.EMISSIVE = false;
  42498. }
  42499. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42500. if (this._metallicTexture) {
  42501. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  42502. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  42503. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  42504. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  42505. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  42506. }
  42507. else if (this._reflectivityTexture) {
  42508. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  42509. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  42510. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  42511. }
  42512. else {
  42513. defines.REFLECTIVITY = false;
  42514. }
  42515. if (this._microSurfaceTexture) {
  42516. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  42517. }
  42518. else {
  42519. defines.MICROSURFACEMAP = false;
  42520. }
  42521. }
  42522. else {
  42523. defines.REFLECTIVITY = false;
  42524. defines.MICROSURFACEMAP = false;
  42525. }
  42526. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42527. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42528. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42529. defines.PARALLAX = true;
  42530. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  42531. }
  42532. else {
  42533. defines.PARALLAX = false;
  42534. }
  42535. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42536. }
  42537. else {
  42538. defines.BUMP = false;
  42539. }
  42540. var refractionTexture = this._getRefractionTexture();
  42541. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42542. defines.REFRACTION = true;
  42543. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  42544. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  42545. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  42546. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  42547. if (this._linkRefractionWithTransparency) {
  42548. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  42549. }
  42550. }
  42551. else {
  42552. defines.REFRACTION = false;
  42553. }
  42554. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42555. defines.ENVIRONMENTBRDF = true;
  42556. }
  42557. else {
  42558. defines.ENVIRONMENTBRDF = false;
  42559. }
  42560. if (this._shouldUseAlphaFromAlbedoTexture()) {
  42561. defines.ALPHAFROMALBEDO = true;
  42562. }
  42563. else {
  42564. defines.ALPHAFROMALBEDO = false;
  42565. }
  42566. }
  42567. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42568. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  42569. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  42570. if (!this.backFaceCulling && this._twoSidedLighting) {
  42571. defines.TWOSIDEDLIGHTING = true;
  42572. }
  42573. else {
  42574. defines.TWOSIDEDLIGHTING = false;
  42575. }
  42576. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  42577. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42578. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  42579. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  42580. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  42581. }
  42582. if (defines._areImageProcessingDirty) {
  42583. this._imageProcessingConfiguration.prepareDefines(defines);
  42584. }
  42585. defines.FORCENORMALFORWARD = this._forceNormalForward;
  42586. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  42587. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  42588. // Misc.
  42589. if (defines._areMiscDirty) {
  42590. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  42591. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42592. }
  42593. // Values that need to be evaluated on every frame
  42594. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  42595. // Attribs
  42596. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  42597. };
  42598. /**
  42599. * Force shader compilation
  42600. */
  42601. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  42602. var _this = this;
  42603. var localOptions = __assign({ clipPlane: false }, options);
  42604. var defines = new PBRMaterialDefines();
  42605. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  42606. if (effect.isReady()) {
  42607. if (onCompiled) {
  42608. onCompiled(this);
  42609. }
  42610. }
  42611. else {
  42612. effect.onCompileObservable.add(function () {
  42613. if (onCompiled) {
  42614. onCompiled(_this);
  42615. }
  42616. });
  42617. }
  42618. };
  42619. /**
  42620. * Initializes the uniform buffer layout for the shader.
  42621. */
  42622. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  42623. // Order is important !
  42624. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  42625. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  42626. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42627. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42628. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42629. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  42630. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  42631. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42632. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42633. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42634. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42635. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42636. this._uniformBuffer.addUniform("albedoMatrix", 16);
  42637. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42638. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42639. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42640. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42641. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  42642. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  42643. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42644. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42645. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42646. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42647. this._uniformBuffer.addUniform("vReflectionColor", 3);
  42648. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  42649. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  42650. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  42651. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  42652. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  42653. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42654. this._uniformBuffer.addUniform("pointSize", 1);
  42655. this._uniformBuffer.create();
  42656. };
  42657. /**
  42658. * Unbinds the textures.
  42659. */
  42660. PBRBaseMaterial.prototype.unbind = function () {
  42661. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42662. this._uniformBuffer.setTexture("reflectionSampler", null);
  42663. }
  42664. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42665. this._uniformBuffer.setTexture("refractionSampler", null);
  42666. }
  42667. _super.prototype.unbind.call(this);
  42668. };
  42669. /**
  42670. * Binds the submesh data.
  42671. * @param world - The world matrix.
  42672. * @param mesh - The BJS mesh.
  42673. * @param subMesh - A submesh of the BJS mesh.
  42674. */
  42675. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42676. var scene = this.getScene();
  42677. var defines = subMesh._materialDefines;
  42678. if (!defines) {
  42679. return;
  42680. }
  42681. var effect = subMesh.effect;
  42682. if (!effect) {
  42683. return;
  42684. }
  42685. this._activeEffect = effect;
  42686. // Matrices
  42687. this.bindOnlyWorldMatrix(world);
  42688. // Normal Matrix
  42689. if (defines.OBJECTSPACE_NORMALMAP) {
  42690. world.toNormalMatrix(this._normalMatrix);
  42691. this.bindOnlyNormalMatrix(this._normalMatrix);
  42692. }
  42693. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42694. // Bones
  42695. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  42696. var reflectionTexture = null;
  42697. if (mustRebind) {
  42698. this._uniformBuffer.bindToEffect(effect, "Material");
  42699. this.bindViewProjection(effect);
  42700. reflectionTexture = this._getReflectionTexture();
  42701. var refractionTexture = this._getRefractionTexture();
  42702. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42703. // Texture uniforms
  42704. if (scene.texturesEnabled) {
  42705. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42706. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  42707. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  42708. }
  42709. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42710. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  42711. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42712. }
  42713. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42714. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42715. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42716. }
  42717. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42718. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  42719. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  42720. if (reflectionTexture.boundingBoxSize) {
  42721. var cubeTexture = reflectionTexture;
  42722. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42723. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42724. }
  42725. var polynomials = reflectionTexture.sphericalPolynomial;
  42726. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  42727. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  42728. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  42729. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  42730. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  42731. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  42732. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  42733. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  42734. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  42735. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  42736. }
  42737. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  42738. }
  42739. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42740. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42741. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42742. }
  42743. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42744. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42745. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42746. }
  42747. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42748. if (this._metallicTexture) {
  42749. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42750. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42751. }
  42752. else if (this._reflectivityTexture) {
  42753. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42754. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42755. }
  42756. if (this._microSurfaceTexture) {
  42757. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42758. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42759. }
  42760. }
  42761. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42762. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42763. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42764. if (scene._mirroredCameraPosition) {
  42765. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42766. }
  42767. else {
  42768. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42769. }
  42770. }
  42771. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42772. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42773. var depth = 1.0;
  42774. if (!refractionTexture.isCube) {
  42775. if (refractionTexture.depth) {
  42776. depth = refractionTexture.depth;
  42777. }
  42778. }
  42779. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42780. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42781. }
  42782. }
  42783. // Point size
  42784. if (this.pointsCloud) {
  42785. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42786. }
  42787. // Colors
  42788. if (defines.METALLICWORKFLOW) {
  42789. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42790. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42791. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42792. }
  42793. else {
  42794. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42795. }
  42796. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42797. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42798. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42799. // Misc
  42800. this._lightingInfos.x = this._directIntensity;
  42801. this._lightingInfos.y = this._emissiveIntensity;
  42802. this._lightingInfos.z = this._environmentIntensity;
  42803. this._lightingInfos.w = this._specularIntensity;
  42804. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42805. }
  42806. // Textures
  42807. if (scene.texturesEnabled) {
  42808. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42809. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42810. }
  42811. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42812. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42813. }
  42814. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42815. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42816. }
  42817. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42818. if (defines.LODBASEDMICROSFURACE) {
  42819. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42820. }
  42821. else {
  42822. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42823. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42824. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42825. }
  42826. }
  42827. if (defines.ENVIRONMENTBRDF) {
  42828. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42829. }
  42830. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42831. if (defines.LODBASEDMICROSFURACE) {
  42832. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42833. }
  42834. else {
  42835. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42836. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42837. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42838. }
  42839. }
  42840. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42841. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42842. }
  42843. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42844. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42845. }
  42846. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42847. if (this._metallicTexture) {
  42848. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42849. }
  42850. else if (this._reflectivityTexture) {
  42851. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42852. }
  42853. if (this._microSurfaceTexture) {
  42854. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42855. }
  42856. }
  42857. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42858. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42859. }
  42860. }
  42861. // Clip plane
  42862. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42863. // Colors
  42864. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42865. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42866. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42867. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42868. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42869. }
  42870. if (mustRebind || !this.isFrozen) {
  42871. // Lights
  42872. if (scene.lightsEnabled && !this._disableLighting) {
  42873. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42874. }
  42875. // View
  42876. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42877. this.bindView(effect);
  42878. }
  42879. // Fog
  42880. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42881. // Morph targets
  42882. if (defines.NUM_MORPH_INFLUENCERS) {
  42883. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42884. }
  42885. // image processing
  42886. this._imageProcessingConfiguration.bind(this._activeEffect);
  42887. // Log. depth
  42888. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42889. }
  42890. this._uniformBuffer.update();
  42891. this._afterBind(mesh);
  42892. };
  42893. /**
  42894. * Returns the animatable textures.
  42895. * @returns - Array of animatable textures.
  42896. */
  42897. PBRBaseMaterial.prototype.getAnimatables = function () {
  42898. var results = [];
  42899. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42900. results.push(this._albedoTexture);
  42901. }
  42902. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42903. results.push(this._ambientTexture);
  42904. }
  42905. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42906. results.push(this._opacityTexture);
  42907. }
  42908. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42909. results.push(this._reflectionTexture);
  42910. }
  42911. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42912. results.push(this._emissiveTexture);
  42913. }
  42914. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42915. results.push(this._metallicTexture);
  42916. }
  42917. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42918. results.push(this._reflectivityTexture);
  42919. }
  42920. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42921. results.push(this._bumpTexture);
  42922. }
  42923. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42924. results.push(this._lightmapTexture);
  42925. }
  42926. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42927. results.push(this._refractionTexture);
  42928. }
  42929. return results;
  42930. };
  42931. /**
  42932. * Returns the texture used for reflections.
  42933. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42934. */
  42935. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42936. if (this._reflectionTexture) {
  42937. return this._reflectionTexture;
  42938. }
  42939. return this.getScene().environmentTexture;
  42940. };
  42941. /**
  42942. * Returns the texture used for refraction or null if none is used.
  42943. * @returns - Refection texture if present. If no refraction texture and refraction
  42944. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42945. */
  42946. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42947. if (this._refractionTexture) {
  42948. return this._refractionTexture;
  42949. }
  42950. if (this._linkRefractionWithTransparency) {
  42951. return this.getScene().environmentTexture;
  42952. }
  42953. return null;
  42954. };
  42955. /**
  42956. * Disposes the resources of the material.
  42957. * @param forceDisposeEffect - Forces the disposal of effects.
  42958. * @param forceDisposeTextures - Forces the disposal of all textures.
  42959. */
  42960. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42961. if (forceDisposeTextures) {
  42962. if (this._albedoTexture) {
  42963. this._albedoTexture.dispose();
  42964. }
  42965. if (this._ambientTexture) {
  42966. this._ambientTexture.dispose();
  42967. }
  42968. if (this._opacityTexture) {
  42969. this._opacityTexture.dispose();
  42970. }
  42971. if (this._reflectionTexture) {
  42972. this._reflectionTexture.dispose();
  42973. }
  42974. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42975. this._environmentBRDFTexture.dispose();
  42976. }
  42977. if (this._emissiveTexture) {
  42978. this._emissiveTexture.dispose();
  42979. }
  42980. if (this._metallicTexture) {
  42981. this._metallicTexture.dispose();
  42982. }
  42983. if (this._reflectivityTexture) {
  42984. this._reflectivityTexture.dispose();
  42985. }
  42986. if (this._bumpTexture) {
  42987. this._bumpTexture.dispose();
  42988. }
  42989. if (this._lightmapTexture) {
  42990. this._lightmapTexture.dispose();
  42991. }
  42992. if (this._refractionTexture) {
  42993. this._refractionTexture.dispose();
  42994. }
  42995. }
  42996. this._renderTargets.dispose();
  42997. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42998. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42999. }
  43000. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43001. };
  43002. /**
  43003. * Stores the reflectivity values based on metallic roughness workflow.
  43004. */
  43005. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  43006. __decorate([
  43007. BABYLON.serializeAsImageProcessingConfiguration()
  43008. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  43009. __decorate([
  43010. BABYLON.serialize()
  43011. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  43012. __decorate([
  43013. BABYLON.serialize()
  43014. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  43015. return PBRBaseMaterial;
  43016. }(BABYLON.PushMaterial));
  43017. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  43018. })(BABYLON || (BABYLON = {}));
  43019. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  43020. "use strict";
  43021. var BABYLON;
  43022. (function (BABYLON) {
  43023. /**
  43024. * The Physically based simple base material of BJS.
  43025. *
  43026. * This enables better naming and convention enforcements on top of the pbrMaterial.
  43027. * It is used as the base class for both the specGloss and metalRough conventions.
  43028. */
  43029. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  43030. __extends(PBRBaseSimpleMaterial, _super);
  43031. /**
  43032. * Instantiates a new PBRMaterial instance.
  43033. *
  43034. * @param name The material name
  43035. * @param scene The scene the material will be use in.
  43036. */
  43037. function PBRBaseSimpleMaterial(name, scene) {
  43038. var _this = _super.call(this, name, scene) || this;
  43039. /**
  43040. * Number of Simultaneous lights allowed on the material.
  43041. */
  43042. _this.maxSimultaneousLights = 4;
  43043. /**
  43044. * If sets to true, disables all the lights affecting the material.
  43045. */
  43046. _this.disableLighting = false;
  43047. /**
  43048. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43049. */
  43050. _this.invertNormalMapX = false;
  43051. /**
  43052. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43053. */
  43054. _this.invertNormalMapY = false;
  43055. /**
  43056. * Emissivie color used to self-illuminate the model.
  43057. */
  43058. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43059. /**
  43060. * Occlusion Channel Strenght.
  43061. */
  43062. _this.occlusionStrength = 1.0;
  43063. _this.useLightmapAsShadowmap = false;
  43064. _this._useAlphaFromAlbedoTexture = true;
  43065. _this._useAmbientInGrayScale = true;
  43066. return _this;
  43067. }
  43068. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  43069. /**
  43070. * Gets the current double sided mode.
  43071. */
  43072. get: function () {
  43073. return this._twoSidedLighting;
  43074. },
  43075. /**
  43076. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43077. */
  43078. set: function (value) {
  43079. if (this._twoSidedLighting === value) {
  43080. return;
  43081. }
  43082. this._twoSidedLighting = value;
  43083. this.backFaceCulling = !value;
  43084. this._markAllSubMeshesAsTexturesDirty();
  43085. },
  43086. enumerable: true,
  43087. configurable: true
  43088. });
  43089. /**
  43090. * Return the active textures of the material.
  43091. */
  43092. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  43093. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43094. if (this.environmentTexture) {
  43095. activeTextures.push(this.environmentTexture);
  43096. }
  43097. if (this.normalTexture) {
  43098. activeTextures.push(this.normalTexture);
  43099. }
  43100. if (this.emissiveTexture) {
  43101. activeTextures.push(this.emissiveTexture);
  43102. }
  43103. if (this.occlusionTexture) {
  43104. activeTextures.push(this.occlusionTexture);
  43105. }
  43106. if (this.lightmapTexture) {
  43107. activeTextures.push(this.lightmapTexture);
  43108. }
  43109. return activeTextures;
  43110. };
  43111. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  43112. if (_super.prototype.hasTexture.call(this, texture)) {
  43113. return true;
  43114. }
  43115. if (this.lightmapTexture === texture) {
  43116. return true;
  43117. }
  43118. return false;
  43119. };
  43120. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  43121. return "PBRBaseSimpleMaterial";
  43122. };
  43123. __decorate([
  43124. BABYLON.serialize(),
  43125. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43126. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  43127. __decorate([
  43128. BABYLON.serialize(),
  43129. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43130. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  43131. __decorate([
  43132. BABYLON.serializeAsTexture(),
  43133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  43134. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  43135. __decorate([
  43136. BABYLON.serialize(),
  43137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43138. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  43139. __decorate([
  43140. BABYLON.serialize(),
  43141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43142. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  43143. __decorate([
  43144. BABYLON.serializeAsTexture(),
  43145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  43146. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  43147. __decorate([
  43148. BABYLON.serializeAsColor3("emissive"),
  43149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43150. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  43151. __decorate([
  43152. BABYLON.serializeAsTexture(),
  43153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43154. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  43155. __decorate([
  43156. BABYLON.serialize(),
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  43158. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  43159. __decorate([
  43160. BABYLON.serializeAsTexture(),
  43161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  43162. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  43163. __decorate([
  43164. BABYLON.serialize(),
  43165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  43166. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  43167. __decorate([
  43168. BABYLON.serialize()
  43169. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  43170. __decorate([
  43171. BABYLON.serializeAsTexture(),
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43173. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  43174. __decorate([
  43175. BABYLON.serialize(),
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43177. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43178. return PBRBaseSimpleMaterial;
  43179. }(BABYLON.PBRBaseMaterial));
  43180. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  43181. })(BABYLON || (BABYLON = {}));
  43182. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  43183. "use strict";
  43184. var BABYLON;
  43185. (function (BABYLON) {
  43186. /**
  43187. * The Physically based material of BJS.
  43188. *
  43189. * This offers the main features of a standard PBR material.
  43190. * For more information, please refer to the documentation :
  43191. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43192. */
  43193. var PBRMaterial = /** @class */ (function (_super) {
  43194. __extends(PBRMaterial, _super);
  43195. /**
  43196. * Instantiates a new PBRMaterial instance.
  43197. *
  43198. * @param name The material name
  43199. * @param scene The scene the material will be use in.
  43200. */
  43201. function PBRMaterial(name, scene) {
  43202. var _this = _super.call(this, name, scene) || this;
  43203. /**
  43204. * Intensity of the direct lights e.g. the four lights available in your scene.
  43205. * This impacts both the direct diffuse and specular highlights.
  43206. */
  43207. _this.directIntensity = 1.0;
  43208. /**
  43209. * Intensity of the emissive part of the material.
  43210. * This helps controlling the emissive effect without modifying the emissive color.
  43211. */
  43212. _this.emissiveIntensity = 1.0;
  43213. /**
  43214. * Intensity of the environment e.g. how much the environment will light the object
  43215. * either through harmonics for rough material or through the refelction for shiny ones.
  43216. */
  43217. _this.environmentIntensity = 1.0;
  43218. /**
  43219. * This is a special control allowing the reduction of the specular highlights coming from the
  43220. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43221. */
  43222. _this.specularIntensity = 1.0;
  43223. /**
  43224. * Debug Control allowing disabling the bump map on this material.
  43225. */
  43226. _this.disableBumpMap = false;
  43227. /**
  43228. * AKA Occlusion Texture Intensity in other nomenclature.
  43229. */
  43230. _this.ambientTextureStrength = 1.0;
  43231. /**
  43232. * The color of a material in ambient lighting.
  43233. */
  43234. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43235. /**
  43236. * AKA Diffuse Color in other nomenclature.
  43237. */
  43238. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  43239. /**
  43240. * AKA Specular Color in other nomenclature.
  43241. */
  43242. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43243. /**
  43244. * The color reflected from the material.
  43245. */
  43246. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  43247. /**
  43248. * The color emitted from the material.
  43249. */
  43250. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43251. /**
  43252. * AKA Glossiness in other nomenclature.
  43253. */
  43254. _this.microSurface = 1.0;
  43255. /**
  43256. * source material index of refraction (IOR)' / 'destination material IOR.
  43257. */
  43258. _this.indexOfRefraction = 0.66;
  43259. /**
  43260. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43261. */
  43262. _this.invertRefractionY = false;
  43263. /**
  43264. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43265. * Materials half opaque for instance using refraction could benefit from this control.
  43266. */
  43267. _this.linkRefractionWithTransparency = false;
  43268. _this.useLightmapAsShadowmap = false;
  43269. /**
  43270. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43271. */
  43272. _this.useAlphaFromAlbedoTexture = false;
  43273. /**
  43274. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43275. */
  43276. _this.forceAlphaTest = false;
  43277. /**
  43278. * Defines the alpha limits in alpha test mode.
  43279. */
  43280. _this.alphaCutOff = 0.4;
  43281. /**
  43282. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43283. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43284. */
  43285. _this.useSpecularOverAlpha = true;
  43286. /**
  43287. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43288. */
  43289. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  43290. /**
  43291. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43292. */
  43293. _this.useRoughnessFromMetallicTextureAlpha = true;
  43294. /**
  43295. * Specifies if the metallic texture contains the roughness information in its green channel.
  43296. */
  43297. _this.useRoughnessFromMetallicTextureGreen = false;
  43298. /**
  43299. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43300. */
  43301. _this.useMetallnessFromMetallicTextureBlue = false;
  43302. /**
  43303. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43304. */
  43305. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  43306. /**
  43307. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43308. */
  43309. _this.useAmbientInGrayScale = false;
  43310. /**
  43311. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43312. * The material will try to infer what glossiness each pixel should be.
  43313. */
  43314. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  43315. /**
  43316. * BJS is using an harcoded light falloff based on a manually sets up range.
  43317. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43318. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43319. */
  43320. _this.usePhysicalLightFalloff = true;
  43321. /**
  43322. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43323. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43324. */
  43325. _this.useRadianceOverAlpha = true;
  43326. /**
  43327. * Allows using an object space normal map (instead of tangent space).
  43328. */
  43329. _this.useObjectSpaceNormalMap = false;
  43330. /**
  43331. * Allows using the bump map in parallax mode.
  43332. */
  43333. _this.useParallax = false;
  43334. /**
  43335. * Allows using the bump map in parallax occlusion mode.
  43336. */
  43337. _this.useParallaxOcclusion = false;
  43338. /**
  43339. * Controls the scale bias of the parallax mode.
  43340. */
  43341. _this.parallaxScaleBias = 0.05;
  43342. /**
  43343. * If sets to true, disables all the lights affecting the material.
  43344. */
  43345. _this.disableLighting = false;
  43346. /**
  43347. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43348. */
  43349. _this.forceIrradianceInFragment = false;
  43350. /**
  43351. * Number of Simultaneous lights allowed on the material.
  43352. */
  43353. _this.maxSimultaneousLights = 4;
  43354. /**
  43355. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  43356. */
  43357. _this.invertNormalMapX = false;
  43358. /**
  43359. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  43360. */
  43361. _this.invertNormalMapY = false;
  43362. /**
  43363. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43364. */
  43365. _this.twoSidedLighting = false;
  43366. /**
  43367. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43368. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43369. */
  43370. _this.useAlphaFresnel = false;
  43371. /**
  43372. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43373. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43374. */
  43375. _this.useLinearAlphaFresnel = false;
  43376. /**
  43377. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43378. * And/Or occlude the blended part.
  43379. */
  43380. _this.environmentBRDFTexture = null;
  43381. /**
  43382. * Force normal to face away from face.
  43383. */
  43384. _this.forceNormalForward = false;
  43385. /**
  43386. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43387. * makes the reflect vector face the model (under horizon).
  43388. */
  43389. _this.useHorizonOcclusion = true;
  43390. /**
  43391. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43392. * too much the area relying on ambient texture to define their ambient occlusion.
  43393. */
  43394. _this.useRadianceOcclusion = true;
  43395. /**
  43396. * If set to true, no lighting calculations will be applied.
  43397. */
  43398. _this.unlit = false;
  43399. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43400. return _this;
  43401. }
  43402. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  43403. /**
  43404. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  43405. */
  43406. get: function () {
  43407. return this._PBRMATERIAL_OPAQUE;
  43408. },
  43409. enumerable: true,
  43410. configurable: true
  43411. });
  43412. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  43413. /**
  43414. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43415. */
  43416. get: function () {
  43417. return this._PBRMATERIAL_ALPHATEST;
  43418. },
  43419. enumerable: true,
  43420. configurable: true
  43421. });
  43422. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  43423. /**
  43424. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43425. */
  43426. get: function () {
  43427. return this._PBRMATERIAL_ALPHABLEND;
  43428. },
  43429. enumerable: true,
  43430. configurable: true
  43431. });
  43432. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  43433. /**
  43434. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43435. * They are also discarded below the alpha cutoff threshold to improve performances.
  43436. */
  43437. get: function () {
  43438. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  43439. },
  43440. enumerable: true,
  43441. configurable: true
  43442. });
  43443. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  43444. /**
  43445. * Gets the image processing configuration used either in this material.
  43446. */
  43447. get: function () {
  43448. return this._imageProcessingConfiguration;
  43449. },
  43450. /**
  43451. * Sets the Default image processing configuration used either in the this material.
  43452. *
  43453. * If sets to null, the scene one is in use.
  43454. */
  43455. set: function (value) {
  43456. this._attachImageProcessingConfiguration(value);
  43457. // Ensure the effect will be rebuilt.
  43458. this._markAllSubMeshesAsTexturesDirty();
  43459. },
  43460. enumerable: true,
  43461. configurable: true
  43462. });
  43463. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  43464. /**
  43465. * Gets wether the color curves effect is enabled.
  43466. */
  43467. get: function () {
  43468. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43469. },
  43470. /**
  43471. * Sets wether the color curves effect is enabled.
  43472. */
  43473. set: function (value) {
  43474. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43475. },
  43476. enumerable: true,
  43477. configurable: true
  43478. });
  43479. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  43480. /**
  43481. * Gets wether the color grading effect is enabled.
  43482. */
  43483. get: function () {
  43484. return this.imageProcessingConfiguration.colorGradingEnabled;
  43485. },
  43486. /**
  43487. * Gets wether the color grading effect is enabled.
  43488. */
  43489. set: function (value) {
  43490. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43491. },
  43492. enumerable: true,
  43493. configurable: true
  43494. });
  43495. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  43496. /**
  43497. * Gets wether tonemapping is enabled or not.
  43498. */
  43499. get: function () {
  43500. return this._imageProcessingConfiguration.toneMappingEnabled;
  43501. },
  43502. /**
  43503. * Sets wether tonemapping is enabled or not
  43504. */
  43505. set: function (value) {
  43506. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43507. },
  43508. enumerable: true,
  43509. configurable: true
  43510. });
  43511. ;
  43512. ;
  43513. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  43514. /**
  43515. * The camera exposure used on this material.
  43516. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43517. * This corresponds to a photographic exposure.
  43518. */
  43519. get: function () {
  43520. return this._imageProcessingConfiguration.exposure;
  43521. },
  43522. /**
  43523. * The camera exposure used on this material.
  43524. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43525. * This corresponds to a photographic exposure.
  43526. */
  43527. set: function (value) {
  43528. this._imageProcessingConfiguration.exposure = value;
  43529. },
  43530. enumerable: true,
  43531. configurable: true
  43532. });
  43533. ;
  43534. ;
  43535. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  43536. /**
  43537. * Gets The camera contrast used on this material.
  43538. */
  43539. get: function () {
  43540. return this._imageProcessingConfiguration.contrast;
  43541. },
  43542. /**
  43543. * Sets The camera contrast used on this material.
  43544. */
  43545. set: function (value) {
  43546. this._imageProcessingConfiguration.contrast = value;
  43547. },
  43548. enumerable: true,
  43549. configurable: true
  43550. });
  43551. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  43552. /**
  43553. * Gets the Color Grading 2D Lookup Texture.
  43554. */
  43555. get: function () {
  43556. return this._imageProcessingConfiguration.colorGradingTexture;
  43557. },
  43558. /**
  43559. * Sets the Color Grading 2D Lookup Texture.
  43560. */
  43561. set: function (value) {
  43562. this._imageProcessingConfiguration.colorGradingTexture = value;
  43563. },
  43564. enumerable: true,
  43565. configurable: true
  43566. });
  43567. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  43568. /**
  43569. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43570. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43571. * 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;
  43572. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43573. */
  43574. get: function () {
  43575. return this._imageProcessingConfiguration.colorCurves;
  43576. },
  43577. /**
  43578. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43579. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43580. * 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;
  43581. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43582. */
  43583. set: function (value) {
  43584. this._imageProcessingConfiguration.colorCurves = value;
  43585. },
  43586. enumerable: true,
  43587. configurable: true
  43588. });
  43589. /**
  43590. * Returns the name of this material class.
  43591. */
  43592. PBRMaterial.prototype.getClassName = function () {
  43593. return "PBRMaterial";
  43594. };
  43595. /**
  43596. * Returns an array of the actively used textures.
  43597. * @returns - Array of BaseTextures
  43598. */
  43599. PBRMaterial.prototype.getActiveTextures = function () {
  43600. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43601. if (this._albedoTexture) {
  43602. activeTextures.push(this._albedoTexture);
  43603. }
  43604. if (this._ambientTexture) {
  43605. activeTextures.push(this._ambientTexture);
  43606. }
  43607. if (this._opacityTexture) {
  43608. activeTextures.push(this._opacityTexture);
  43609. }
  43610. if (this._reflectionTexture) {
  43611. activeTextures.push(this._reflectionTexture);
  43612. }
  43613. if (this._emissiveTexture) {
  43614. activeTextures.push(this._emissiveTexture);
  43615. }
  43616. if (this._reflectivityTexture) {
  43617. activeTextures.push(this._reflectivityTexture);
  43618. }
  43619. if (this._metallicTexture) {
  43620. activeTextures.push(this._metallicTexture);
  43621. }
  43622. if (this._microSurfaceTexture) {
  43623. activeTextures.push(this._microSurfaceTexture);
  43624. }
  43625. if (this._bumpTexture) {
  43626. activeTextures.push(this._bumpTexture);
  43627. }
  43628. if (this._lightmapTexture) {
  43629. activeTextures.push(this._lightmapTexture);
  43630. }
  43631. if (this._refractionTexture) {
  43632. activeTextures.push(this._refractionTexture);
  43633. }
  43634. return activeTextures;
  43635. };
  43636. /**
  43637. * Checks to see if a texture is used in the material.
  43638. * @param texture - Base texture to use.
  43639. * @returns - Boolean specifying if a texture is used in the material.
  43640. */
  43641. PBRMaterial.prototype.hasTexture = function (texture) {
  43642. if (_super.prototype.hasTexture.call(this, texture)) {
  43643. return true;
  43644. }
  43645. if (this._albedoTexture === texture) {
  43646. return true;
  43647. }
  43648. if (this._ambientTexture === texture) {
  43649. return true;
  43650. }
  43651. if (this._opacityTexture === texture) {
  43652. return true;
  43653. }
  43654. if (this._reflectionTexture === texture) {
  43655. return true;
  43656. }
  43657. if (this._reflectivityTexture === texture) {
  43658. return true;
  43659. }
  43660. if (this._metallicTexture === texture) {
  43661. return true;
  43662. }
  43663. if (this._microSurfaceTexture === texture) {
  43664. return true;
  43665. }
  43666. if (this._bumpTexture === texture) {
  43667. return true;
  43668. }
  43669. if (this._lightmapTexture === texture) {
  43670. return true;
  43671. }
  43672. if (this._refractionTexture === texture) {
  43673. return true;
  43674. }
  43675. return false;
  43676. };
  43677. /**
  43678. * Makes a duplicate of the current material.
  43679. * @param name - name to use for the new material.
  43680. */
  43681. PBRMaterial.prototype.clone = function (name) {
  43682. var _this = this;
  43683. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  43684. clone.id = name;
  43685. clone.name = name;
  43686. return clone;
  43687. };
  43688. /**
  43689. * Serializes this PBR Material.
  43690. * @returns - An object with the serialized material.
  43691. */
  43692. PBRMaterial.prototype.serialize = function () {
  43693. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43694. serializationObject.customType = "BABYLON.PBRMaterial";
  43695. return serializationObject;
  43696. };
  43697. // Statics
  43698. /**
  43699. * Parses a PBR Material from a serialized object.
  43700. * @param source - Serialized object.
  43701. * @param scene - BJS scene instance.
  43702. * @param rootUrl - url for the scene object
  43703. * @returns - PBRMaterial
  43704. */
  43705. PBRMaterial.Parse = function (source, scene, rootUrl) {
  43706. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  43707. };
  43708. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  43709. /**
  43710. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  43711. */
  43712. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  43713. /**
  43714. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  43715. */
  43716. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  43717. /**
  43718. * 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.
  43719. * They are also discarded below the alpha cutoff threshold to improve performances.
  43720. */
  43721. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  43722. __decorate([
  43723. BABYLON.serialize(),
  43724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43725. ], PBRMaterial.prototype, "directIntensity", void 0);
  43726. __decorate([
  43727. BABYLON.serialize(),
  43728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43729. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  43730. __decorate([
  43731. BABYLON.serialize(),
  43732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43733. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  43734. __decorate([
  43735. BABYLON.serialize(),
  43736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43737. ], PBRMaterial.prototype, "specularIntensity", void 0);
  43738. __decorate([
  43739. BABYLON.serialize(),
  43740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43741. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  43742. __decorate([
  43743. BABYLON.serializeAsTexture(),
  43744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43745. ], PBRMaterial.prototype, "albedoTexture", void 0);
  43746. __decorate([
  43747. BABYLON.serializeAsTexture(),
  43748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43749. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43750. __decorate([
  43751. BABYLON.serialize(),
  43752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43753. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43754. __decorate([
  43755. BABYLON.serializeAsTexture(),
  43756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43757. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43758. __decorate([
  43759. BABYLON.serializeAsTexture(),
  43760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43761. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43762. __decorate([
  43763. BABYLON.serializeAsTexture(),
  43764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43765. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43766. __decorate([
  43767. BABYLON.serializeAsTexture(),
  43768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43769. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43770. __decorate([
  43771. BABYLON.serializeAsTexture(),
  43772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43773. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43774. __decorate([
  43775. BABYLON.serialize(),
  43776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43777. ], PBRMaterial.prototype, "metallic", void 0);
  43778. __decorate([
  43779. BABYLON.serialize(),
  43780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43781. ], PBRMaterial.prototype, "roughness", void 0);
  43782. __decorate([
  43783. BABYLON.serializeAsTexture(),
  43784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43785. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43786. __decorate([
  43787. BABYLON.serializeAsTexture(),
  43788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43789. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43790. __decorate([
  43791. BABYLON.serializeAsTexture(),
  43792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43793. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43794. __decorate([
  43795. BABYLON.serializeAsTexture(),
  43796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43797. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43798. __decorate([
  43799. BABYLON.serializeAsColor3("ambient"),
  43800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43801. ], PBRMaterial.prototype, "ambientColor", void 0);
  43802. __decorate([
  43803. BABYLON.serializeAsColor3("albedo"),
  43804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43805. ], PBRMaterial.prototype, "albedoColor", void 0);
  43806. __decorate([
  43807. BABYLON.serializeAsColor3("reflectivity"),
  43808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43809. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43810. __decorate([
  43811. BABYLON.serializeAsColor3("reflection"),
  43812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43813. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43814. __decorate([
  43815. BABYLON.serializeAsColor3("emissive"),
  43816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43817. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43818. __decorate([
  43819. BABYLON.serialize(),
  43820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43821. ], PBRMaterial.prototype, "microSurface", void 0);
  43822. __decorate([
  43823. BABYLON.serialize(),
  43824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43825. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43826. __decorate([
  43827. BABYLON.serialize(),
  43828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43829. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43830. __decorate([
  43831. BABYLON.serialize(),
  43832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43833. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43834. __decorate([
  43835. BABYLON.serialize(),
  43836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43837. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43838. __decorate([
  43839. BABYLON.serialize(),
  43840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43841. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43842. __decorate([
  43843. BABYLON.serialize(),
  43844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43845. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43846. __decorate([
  43847. BABYLON.serialize(),
  43848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43849. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43850. __decorate([
  43851. BABYLON.serialize(),
  43852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43853. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43854. __decorate([
  43855. BABYLON.serialize(),
  43856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43857. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43858. __decorate([
  43859. BABYLON.serialize(),
  43860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43861. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43862. __decorate([
  43863. BABYLON.serialize(),
  43864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43865. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43866. __decorate([
  43867. BABYLON.serialize(),
  43868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43869. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43870. __decorate([
  43871. BABYLON.serialize(),
  43872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43873. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43874. __decorate([
  43875. BABYLON.serialize(),
  43876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43877. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43878. __decorate([
  43879. BABYLON.serialize(),
  43880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43881. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43882. __decorate([
  43883. BABYLON.serialize(),
  43884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43885. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43886. __decorate([
  43887. BABYLON.serialize(),
  43888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43889. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43890. __decorate([
  43891. BABYLON.serialize(),
  43892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43893. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43894. __decorate([
  43895. BABYLON.serialize(),
  43896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43897. ], PBRMaterial.prototype, "useParallax", void 0);
  43898. __decorate([
  43899. BABYLON.serialize(),
  43900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43901. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43902. __decorate([
  43903. BABYLON.serialize(),
  43904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43905. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43906. __decorate([
  43907. BABYLON.serialize(),
  43908. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43909. ], PBRMaterial.prototype, "disableLighting", void 0);
  43910. __decorate([
  43911. BABYLON.serialize(),
  43912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43913. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43914. __decorate([
  43915. BABYLON.serialize(),
  43916. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43917. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43918. __decorate([
  43919. BABYLON.serialize(),
  43920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43921. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43922. __decorate([
  43923. BABYLON.serialize(),
  43924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43925. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43926. __decorate([
  43927. BABYLON.serialize(),
  43928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43929. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43930. __decorate([
  43931. BABYLON.serialize(),
  43932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43933. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43934. __decorate([
  43935. BABYLON.serialize(),
  43936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43937. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43938. __decorate([
  43939. BABYLON.serializeAsTexture(),
  43940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43941. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43942. __decorate([
  43943. BABYLON.serialize(),
  43944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43945. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43946. __decorate([
  43947. BABYLON.serialize(),
  43948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43949. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43950. __decorate([
  43951. BABYLON.serialize(),
  43952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43953. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43954. __decorate([
  43955. BABYLON.serialize(),
  43956. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43957. ], PBRMaterial.prototype, "unlit", void 0);
  43958. return PBRMaterial;
  43959. }(BABYLON.PBRBaseMaterial));
  43960. BABYLON.PBRMaterial = PBRMaterial;
  43961. })(BABYLON || (BABYLON = {}));
  43962. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43963. "use strict";
  43964. var BABYLON;
  43965. (function (BABYLON) {
  43966. /**
  43967. * The PBR material of BJS following the metal roughness convention.
  43968. *
  43969. * This fits to the PBR convention in the GLTF definition:
  43970. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43971. */
  43972. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43973. __extends(PBRMetallicRoughnessMaterial, _super);
  43974. /**
  43975. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43976. *
  43977. * @param name The material name
  43978. * @param scene The scene the material will be use in.
  43979. */
  43980. function PBRMetallicRoughnessMaterial(name, scene) {
  43981. var _this = _super.call(this, name, scene) || this;
  43982. _this._useRoughnessFromMetallicTextureAlpha = false;
  43983. _this._useRoughnessFromMetallicTextureGreen = true;
  43984. _this._useMetallnessFromMetallicTextureBlue = true;
  43985. _this.metallic = 1.0;
  43986. _this.roughness = 1.0;
  43987. return _this;
  43988. }
  43989. /**
  43990. * Return the currrent class name of the material.
  43991. */
  43992. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43993. return "PBRMetallicRoughnessMaterial";
  43994. };
  43995. /**
  43996. * Return the active textures of the material.
  43997. */
  43998. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43999. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44000. if (this.baseTexture) {
  44001. activeTextures.push(this.baseTexture);
  44002. }
  44003. if (this.metallicRoughnessTexture) {
  44004. activeTextures.push(this.metallicRoughnessTexture);
  44005. }
  44006. return activeTextures;
  44007. };
  44008. /**
  44009. * Checks to see if a texture is used in the material.
  44010. * @param texture - Base texture to use.
  44011. * @returns - Boolean specifying if a texture is used in the material.
  44012. */
  44013. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  44014. if (_super.prototype.hasTexture.call(this, texture)) {
  44015. return true;
  44016. }
  44017. if (this.baseTexture === texture) {
  44018. return true;
  44019. }
  44020. if (this.metallicRoughnessTexture === texture) {
  44021. return true;
  44022. }
  44023. return false;
  44024. };
  44025. /**
  44026. * Makes a duplicate of the current material.
  44027. * @param name - name to use for the new material.
  44028. */
  44029. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  44030. var _this = this;
  44031. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  44032. clone.id = name;
  44033. clone.name = name;
  44034. return clone;
  44035. };
  44036. /**
  44037. * Serialize the material to a parsable JSON object.
  44038. */
  44039. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  44040. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44041. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  44042. return serializationObject;
  44043. };
  44044. /**
  44045. * Parses a JSON object correponding to the serialize function.
  44046. */
  44047. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  44048. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  44049. };
  44050. __decorate([
  44051. BABYLON.serializeAsColor3(),
  44052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  44053. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  44054. __decorate([
  44055. BABYLON.serializeAsTexture(),
  44056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  44057. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  44058. __decorate([
  44059. BABYLON.serialize(),
  44060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44061. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  44062. __decorate([
  44063. BABYLON.serialize(),
  44064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44065. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  44066. __decorate([
  44067. BABYLON.serializeAsTexture(),
  44068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  44069. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  44070. return PBRMetallicRoughnessMaterial;
  44071. }(BABYLON.PBRBaseSimpleMaterial));
  44072. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  44073. })(BABYLON || (BABYLON = {}));
  44074. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  44075. "use strict";
  44076. var BABYLON;
  44077. (function (BABYLON) {
  44078. /**
  44079. * The PBR material of BJS following the specular glossiness convention.
  44080. *
  44081. * This fits to the PBR convention in the GLTF definition:
  44082. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  44083. */
  44084. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  44085. __extends(PBRSpecularGlossinessMaterial, _super);
  44086. /**
  44087. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  44088. *
  44089. * @param name The material name
  44090. * @param scene The scene the material will be use in.
  44091. */
  44092. function PBRSpecularGlossinessMaterial(name, scene) {
  44093. var _this = _super.call(this, name, scene) || this;
  44094. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  44095. return _this;
  44096. }
  44097. /**
  44098. * Return the currrent class name of the material.
  44099. */
  44100. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  44101. return "PBRSpecularGlossinessMaterial";
  44102. };
  44103. /**
  44104. * Return the active textures of the material.
  44105. */
  44106. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  44107. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44108. if (this.diffuseTexture) {
  44109. activeTextures.push(this.diffuseTexture);
  44110. }
  44111. if (this.specularGlossinessTexture) {
  44112. activeTextures.push(this.specularGlossinessTexture);
  44113. }
  44114. return activeTextures;
  44115. };
  44116. /**
  44117. * Checks to see if a texture is used in the material.
  44118. * @param texture - Base texture to use.
  44119. * @returns - Boolean specifying if a texture is used in the material.
  44120. */
  44121. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  44122. if (_super.prototype.hasTexture.call(this, texture)) {
  44123. return true;
  44124. }
  44125. if (this.diffuseTexture === texture) {
  44126. return true;
  44127. }
  44128. if (this.specularGlossinessTexture === texture) {
  44129. return true;
  44130. }
  44131. return false;
  44132. };
  44133. /**
  44134. * Makes a duplicate of the current material.
  44135. * @param name - name to use for the new material.
  44136. */
  44137. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  44138. var _this = this;
  44139. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  44140. clone.id = name;
  44141. clone.name = name;
  44142. return clone;
  44143. };
  44144. /**
  44145. * Serialize the material to a parsable JSON object.
  44146. */
  44147. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  44148. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  44149. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  44150. return serializationObject;
  44151. };
  44152. /**
  44153. * Parses a JSON object correponding to the serialize function.
  44154. */
  44155. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  44156. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  44157. };
  44158. __decorate([
  44159. BABYLON.serializeAsColor3("diffuse"),
  44160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  44161. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  44162. __decorate([
  44163. BABYLON.serializeAsTexture(),
  44164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  44165. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  44166. __decorate([
  44167. BABYLON.serializeAsColor3("specular"),
  44168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  44169. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  44170. __decorate([
  44171. BABYLON.serialize(),
  44172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  44173. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  44174. __decorate([
  44175. BABYLON.serializeAsTexture(),
  44176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  44177. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  44178. return PBRSpecularGlossinessMaterial;
  44179. }(BABYLON.PBRBaseSimpleMaterial));
  44180. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  44181. })(BABYLON || (BABYLON = {}));
  44182. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  44183. "use strict";
  44184. var BABYLON;
  44185. (function (BABYLON) {
  44186. BABYLON.CameraInputTypes = {};
  44187. var CameraInputsManager = /** @class */ (function () {
  44188. function CameraInputsManager(camera) {
  44189. this.attached = {};
  44190. this.camera = camera;
  44191. this.checkInputs = function () { };
  44192. }
  44193. /**
  44194. * Add an input method to a camera.
  44195. * builtin inputs example: camera.inputs.addGamepad();
  44196. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  44197. * @param input camera input method
  44198. */
  44199. CameraInputsManager.prototype.add = function (input) {
  44200. var type = input.getSimpleName();
  44201. if (this.attached[type]) {
  44202. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  44203. return;
  44204. }
  44205. this.attached[type] = input;
  44206. input.camera = this.camera;
  44207. //for checkInputs, we are dynamically creating a function
  44208. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  44209. if (input.checkInputs) {
  44210. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  44211. }
  44212. if (this.attachedElement) {
  44213. input.attachControl(this.attachedElement);
  44214. }
  44215. };
  44216. /**
  44217. * Remove a specific input method from a camera
  44218. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  44219. * @param inputToRemove camera input method
  44220. */
  44221. CameraInputsManager.prototype.remove = function (inputToRemove) {
  44222. for (var cam in this.attached) {
  44223. var input = this.attached[cam];
  44224. if (input === inputToRemove) {
  44225. input.detachControl(this.attachedElement);
  44226. input.camera = null;
  44227. delete this.attached[cam];
  44228. this.rebuildInputCheck();
  44229. }
  44230. }
  44231. };
  44232. CameraInputsManager.prototype.removeByType = function (inputType) {
  44233. for (var cam in this.attached) {
  44234. var input = this.attached[cam];
  44235. if (input.getClassName() === inputType) {
  44236. input.detachControl(this.attachedElement);
  44237. input.camera = null;
  44238. delete this.attached[cam];
  44239. this.rebuildInputCheck();
  44240. }
  44241. }
  44242. };
  44243. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  44244. var current = this.checkInputs;
  44245. return function () {
  44246. current();
  44247. fn();
  44248. };
  44249. };
  44250. CameraInputsManager.prototype.attachInput = function (input) {
  44251. if (this.attachedElement) {
  44252. input.attachControl(this.attachedElement, this.noPreventDefault);
  44253. }
  44254. };
  44255. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  44256. if (noPreventDefault === void 0) { noPreventDefault = false; }
  44257. if (this.attachedElement) {
  44258. return;
  44259. }
  44260. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44261. this.attachedElement = element;
  44262. this.noPreventDefault = noPreventDefault;
  44263. for (var cam in this.attached) {
  44264. this.attached[cam].attachControl(element, noPreventDefault);
  44265. }
  44266. };
  44267. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  44268. if (disconnect === void 0) { disconnect = false; }
  44269. if (this.attachedElement !== element) {
  44270. return;
  44271. }
  44272. for (var cam in this.attached) {
  44273. this.attached[cam].detachControl(element);
  44274. if (disconnect) {
  44275. this.attached[cam].camera = null;
  44276. }
  44277. }
  44278. this.attachedElement = null;
  44279. };
  44280. CameraInputsManager.prototype.rebuildInputCheck = function () {
  44281. this.checkInputs = function () { };
  44282. for (var cam in this.attached) {
  44283. var input = this.attached[cam];
  44284. if (input.checkInputs) {
  44285. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  44286. }
  44287. }
  44288. };
  44289. /**
  44290. * Remove all attached input methods from a camera
  44291. */
  44292. CameraInputsManager.prototype.clear = function () {
  44293. if (this.attachedElement) {
  44294. this.detachElement(this.attachedElement, true);
  44295. }
  44296. this.attached = {};
  44297. this.attachedElement = null;
  44298. this.checkInputs = function () { };
  44299. };
  44300. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  44301. var inputs = {};
  44302. for (var cam in this.attached) {
  44303. var input = this.attached[cam];
  44304. var res = BABYLON.SerializationHelper.Serialize(input);
  44305. inputs[input.getClassName()] = res;
  44306. }
  44307. serializedCamera.inputsmgr = inputs;
  44308. };
  44309. CameraInputsManager.prototype.parse = function (parsedCamera) {
  44310. var parsedInputs = parsedCamera.inputsmgr;
  44311. if (parsedInputs) {
  44312. this.clear();
  44313. for (var n in parsedInputs) {
  44314. var construct = BABYLON.CameraInputTypes[n];
  44315. if (construct) {
  44316. var parsedinput = parsedInputs[n];
  44317. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  44318. this.add(input);
  44319. }
  44320. }
  44321. }
  44322. else {
  44323. //2016-03-08 this part is for managing backward compatibility
  44324. for (var n in this.attached) {
  44325. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  44326. if (construct) {
  44327. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  44328. this.remove(this.attached[n]);
  44329. this.add(input);
  44330. }
  44331. }
  44332. }
  44333. };
  44334. return CameraInputsManager;
  44335. }());
  44336. BABYLON.CameraInputsManager = CameraInputsManager;
  44337. })(BABYLON || (BABYLON = {}));
  44338. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  44339. "use strict";
  44340. var BABYLON;
  44341. (function (BABYLON) {
  44342. var TargetCamera = /** @class */ (function (_super) {
  44343. __extends(TargetCamera, _super);
  44344. function TargetCamera(name, position, scene) {
  44345. var _this = _super.call(this, name, position, scene) || this;
  44346. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44347. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  44348. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  44349. _this.speed = 2.0;
  44350. _this.noRotationConstraint = false;
  44351. _this.lockedTarget = null;
  44352. _this._currentTarget = BABYLON.Vector3.Zero();
  44353. _this._viewMatrix = BABYLON.Matrix.Zero();
  44354. _this._camMatrix = BABYLON.Matrix.Zero();
  44355. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  44356. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  44357. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  44358. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  44359. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  44360. _this._lookAtTemp = BABYLON.Matrix.Zero();
  44361. _this._tempMatrix = BABYLON.Matrix.Zero();
  44362. return _this;
  44363. }
  44364. TargetCamera.prototype.getFrontPosition = function (distance) {
  44365. this.getWorldMatrix();
  44366. var direction = this.getTarget().subtract(this.position);
  44367. direction.normalize();
  44368. direction.scaleInPlace(distance);
  44369. return this.globalPosition.add(direction);
  44370. };
  44371. TargetCamera.prototype._getLockedTargetPosition = function () {
  44372. if (!this.lockedTarget) {
  44373. return null;
  44374. }
  44375. if (this.lockedTarget.absolutePosition) {
  44376. this.lockedTarget.computeWorldMatrix();
  44377. }
  44378. return this.lockedTarget.absolutePosition || this.lockedTarget;
  44379. };
  44380. TargetCamera.prototype.storeState = function () {
  44381. this._storedPosition = this.position.clone();
  44382. this._storedRotation = this.rotation.clone();
  44383. if (this.rotationQuaternion) {
  44384. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  44385. }
  44386. return _super.prototype.storeState.call(this);
  44387. };
  44388. /**
  44389. * Restored camera state. You must call storeState() first
  44390. */
  44391. TargetCamera.prototype._restoreStateValues = function () {
  44392. if (!_super.prototype._restoreStateValues.call(this)) {
  44393. return false;
  44394. }
  44395. this.position = this._storedPosition.clone();
  44396. this.rotation = this._storedRotation.clone();
  44397. if (this.rotationQuaternion) {
  44398. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  44399. }
  44400. this.cameraDirection.copyFromFloats(0, 0, 0);
  44401. this.cameraRotation.copyFromFloats(0, 0);
  44402. return true;
  44403. };
  44404. // Cache
  44405. TargetCamera.prototype._initCache = function () {
  44406. _super.prototype._initCache.call(this);
  44407. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44408. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44409. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44410. };
  44411. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  44412. if (!ignoreParentClass) {
  44413. _super.prototype._updateCache.call(this);
  44414. }
  44415. var lockedTargetPosition = this._getLockedTargetPosition();
  44416. if (!lockedTargetPosition) {
  44417. this._cache.lockedTarget = null;
  44418. }
  44419. else {
  44420. if (!this._cache.lockedTarget) {
  44421. this._cache.lockedTarget = lockedTargetPosition.clone();
  44422. }
  44423. else {
  44424. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  44425. }
  44426. }
  44427. this._cache.rotation.copyFrom(this.rotation);
  44428. if (this.rotationQuaternion)
  44429. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  44430. };
  44431. // Synchronized
  44432. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  44433. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  44434. return false;
  44435. }
  44436. var lockedTargetPosition = this._getLockedTargetPosition();
  44437. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  44438. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  44439. };
  44440. // Methods
  44441. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  44442. var engine = this.getEngine();
  44443. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  44444. };
  44445. // Target
  44446. TargetCamera.prototype.setTarget = function (target) {
  44447. this.upVector.normalize();
  44448. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  44449. this._camMatrix.invert();
  44450. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  44451. var vDir = target.subtract(this.position);
  44452. if (vDir.x >= 0.0) {
  44453. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  44454. }
  44455. else {
  44456. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  44457. }
  44458. this.rotation.z = 0;
  44459. if (isNaN(this.rotation.x)) {
  44460. this.rotation.x = 0;
  44461. }
  44462. if (isNaN(this.rotation.y)) {
  44463. this.rotation.y = 0;
  44464. }
  44465. if (isNaN(this.rotation.z)) {
  44466. this.rotation.z = 0;
  44467. }
  44468. if (this.rotationQuaternion) {
  44469. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  44470. }
  44471. };
  44472. /**
  44473. * Return the current target position of the camera. This value is expressed in local space.
  44474. */
  44475. TargetCamera.prototype.getTarget = function () {
  44476. return this._currentTarget;
  44477. };
  44478. TargetCamera.prototype._decideIfNeedsToMove = function () {
  44479. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44480. };
  44481. TargetCamera.prototype._updatePosition = function () {
  44482. if (this.parent) {
  44483. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  44484. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  44485. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  44486. return;
  44487. }
  44488. this.position.addInPlace(this.cameraDirection);
  44489. };
  44490. TargetCamera.prototype._checkInputs = function () {
  44491. var needToMove = this._decideIfNeedsToMove();
  44492. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  44493. // Move
  44494. if (needToMove) {
  44495. this._updatePosition();
  44496. }
  44497. // Rotate
  44498. if (needToRotate) {
  44499. this.rotation.x += this.cameraRotation.x;
  44500. this.rotation.y += this.cameraRotation.y;
  44501. //rotate, if quaternion is set and rotation was used
  44502. if (this.rotationQuaternion) {
  44503. var len = this.rotation.lengthSquared();
  44504. if (len) {
  44505. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  44506. }
  44507. }
  44508. if (!this.noRotationConstraint) {
  44509. var limit = (Math.PI / 2) * 0.95;
  44510. if (this.rotation.x > limit)
  44511. this.rotation.x = limit;
  44512. if (this.rotation.x < -limit)
  44513. this.rotation.x = -limit;
  44514. }
  44515. }
  44516. // Inertia
  44517. if (needToMove) {
  44518. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  44519. this.cameraDirection.x = 0;
  44520. }
  44521. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  44522. this.cameraDirection.y = 0;
  44523. }
  44524. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  44525. this.cameraDirection.z = 0;
  44526. }
  44527. this.cameraDirection.scaleInPlace(this.inertia);
  44528. }
  44529. if (needToRotate) {
  44530. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  44531. this.cameraRotation.x = 0;
  44532. }
  44533. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  44534. this.cameraRotation.y = 0;
  44535. }
  44536. this.cameraRotation.scaleInPlace(this.inertia);
  44537. }
  44538. _super.prototype._checkInputs.call(this);
  44539. };
  44540. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  44541. if (this.rotationQuaternion) {
  44542. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  44543. }
  44544. else {
  44545. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  44546. }
  44547. //update the up vector!
  44548. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  44549. };
  44550. TargetCamera.prototype._getViewMatrix = function () {
  44551. if (this.lockedTarget) {
  44552. this.setTarget(this._getLockedTargetPosition());
  44553. }
  44554. // Compute
  44555. this._updateCameraRotationMatrix();
  44556. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  44557. // Computing target and final matrix
  44558. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  44559. if (this.getScene().useRightHandedSystem) {
  44560. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  44561. }
  44562. else {
  44563. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  44564. }
  44565. return this._viewMatrix;
  44566. };
  44567. /**
  44568. * @override
  44569. * Override Camera.createRigCamera
  44570. */
  44571. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44572. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  44573. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  44574. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  44575. if (!this.rotationQuaternion) {
  44576. this.rotationQuaternion = new BABYLON.Quaternion();
  44577. }
  44578. rigCamera._cameraRigParams = {};
  44579. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  44580. }
  44581. return rigCamera;
  44582. }
  44583. return null;
  44584. };
  44585. /**
  44586. * @override
  44587. * Override Camera._updateRigCameras
  44588. */
  44589. TargetCamera.prototype._updateRigCameras = function () {
  44590. var camLeft = this._rigCameras[0];
  44591. var camRight = this._rigCameras[1];
  44592. switch (this.cameraRigMode) {
  44593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44595. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44596. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44597. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  44598. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  44599. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  44600. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  44601. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  44602. camLeft.setTarget(this.getTarget());
  44603. camRight.setTarget(this.getTarget());
  44604. break;
  44605. case BABYLON.Camera.RIG_MODE_VR:
  44606. if (camLeft.rotationQuaternion) {
  44607. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  44608. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  44609. }
  44610. else {
  44611. camLeft.rotation.copyFrom(this.rotation);
  44612. camRight.rotation.copyFrom(this.rotation);
  44613. }
  44614. camLeft.position.copyFrom(this.position);
  44615. camRight.position.copyFrom(this.position);
  44616. break;
  44617. }
  44618. _super.prototype._updateRigCameras.call(this);
  44619. };
  44620. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  44621. if (!this._rigCamTransformMatrix) {
  44622. this._rigCamTransformMatrix = new BABYLON.Matrix();
  44623. }
  44624. var target = this.getTarget();
  44625. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  44626. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  44627. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  44628. };
  44629. TargetCamera.prototype.getClassName = function () {
  44630. return "TargetCamera";
  44631. };
  44632. __decorate([
  44633. BABYLON.serializeAsVector3()
  44634. ], TargetCamera.prototype, "rotation", void 0);
  44635. __decorate([
  44636. BABYLON.serialize()
  44637. ], TargetCamera.prototype, "speed", void 0);
  44638. __decorate([
  44639. BABYLON.serializeAsMeshReference("lockedTargetId")
  44640. ], TargetCamera.prototype, "lockedTarget", void 0);
  44641. return TargetCamera;
  44642. }(BABYLON.Camera));
  44643. BABYLON.TargetCamera = TargetCamera;
  44644. })(BABYLON || (BABYLON = {}));
  44645. //# sourceMappingURL=babylon.targetCamera.js.map
  44646. "use strict";
  44647. var BABYLON;
  44648. (function (BABYLON) {
  44649. var FreeCameraMouseInput = /** @class */ (function () {
  44650. function FreeCameraMouseInput(touchEnabled) {
  44651. if (touchEnabled === void 0) { touchEnabled = true; }
  44652. this.touchEnabled = touchEnabled;
  44653. this.buttons = [0, 1, 2];
  44654. this.angularSensibility = 2000.0;
  44655. this.previousPosition = null;
  44656. }
  44657. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  44658. var _this = this;
  44659. var engine = this.camera.getEngine();
  44660. if (!this._pointerInput) {
  44661. this._pointerInput = function (p, s) {
  44662. var evt = p.event;
  44663. if (engine.isInVRExclusivePointerMode) {
  44664. return;
  44665. }
  44666. if (!_this.touchEnabled && evt.pointerType === "touch") {
  44667. return;
  44668. }
  44669. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44670. return;
  44671. }
  44672. var srcElement = (evt.srcElement || evt.target);
  44673. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44674. try {
  44675. srcElement.setPointerCapture(evt.pointerId);
  44676. }
  44677. catch (e) {
  44678. //Nothing to do with the error. Execution will continue.
  44679. }
  44680. _this.previousPosition = {
  44681. x: evt.clientX,
  44682. y: evt.clientY
  44683. };
  44684. if (!noPreventDefault) {
  44685. evt.preventDefault();
  44686. element.focus();
  44687. }
  44688. }
  44689. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44690. try {
  44691. srcElement.releasePointerCapture(evt.pointerId);
  44692. }
  44693. catch (e) {
  44694. //Nothing to do with the error.
  44695. }
  44696. _this.previousPosition = null;
  44697. if (!noPreventDefault) {
  44698. evt.preventDefault();
  44699. }
  44700. }
  44701. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44702. if (!_this.previousPosition || engine.isPointerLock) {
  44703. return;
  44704. }
  44705. var offsetX = evt.clientX - _this.previousPosition.x;
  44706. var offsetY = evt.clientY - _this.previousPosition.y;
  44707. if (_this.camera.getScene().useRightHandedSystem) {
  44708. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44709. }
  44710. else {
  44711. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44712. }
  44713. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44714. _this.previousPosition = {
  44715. x: evt.clientX,
  44716. y: evt.clientY
  44717. };
  44718. if (!noPreventDefault) {
  44719. evt.preventDefault();
  44720. }
  44721. }
  44722. };
  44723. }
  44724. this._onMouseMove = function (evt) {
  44725. if (!engine.isPointerLock) {
  44726. return;
  44727. }
  44728. if (engine.isInVRExclusivePointerMode) {
  44729. return;
  44730. }
  44731. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44732. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44733. if (_this.camera.getScene().useRightHandedSystem) {
  44734. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  44735. }
  44736. else {
  44737. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  44738. }
  44739. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  44740. _this.previousPosition = null;
  44741. if (!noPreventDefault) {
  44742. evt.preventDefault();
  44743. }
  44744. };
  44745. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44746. element.addEventListener("mousemove", this._onMouseMove, false);
  44747. };
  44748. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44749. if (this._observer && element) {
  44750. this.camera.getScene().onPointerObservable.remove(this._observer);
  44751. if (this._onMouseMove) {
  44752. element.removeEventListener("mousemove", this._onMouseMove);
  44753. }
  44754. this._observer = null;
  44755. this._onMouseMove = null;
  44756. this.previousPosition = null;
  44757. }
  44758. };
  44759. FreeCameraMouseInput.prototype.getClassName = function () {
  44760. return "FreeCameraMouseInput";
  44761. };
  44762. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44763. return "mouse";
  44764. };
  44765. __decorate([
  44766. BABYLON.serialize()
  44767. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44768. __decorate([
  44769. BABYLON.serialize()
  44770. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44771. return FreeCameraMouseInput;
  44772. }());
  44773. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44774. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44775. })(BABYLON || (BABYLON = {}));
  44776. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44777. "use strict";
  44778. var BABYLON;
  44779. (function (BABYLON) {
  44780. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44781. function FreeCameraKeyboardMoveInput() {
  44782. this._keys = new Array();
  44783. this.keysUp = [38];
  44784. this.keysDown = [40];
  44785. this.keysLeft = [37];
  44786. this.keysRight = [39];
  44787. }
  44788. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44789. var _this = this;
  44790. if (this._onCanvasBlurObserver) {
  44791. return;
  44792. }
  44793. this._scene = this.camera.getScene();
  44794. this._engine = this._scene.getEngine();
  44795. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44796. _this._keys = [];
  44797. });
  44798. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44799. var evt = info.event;
  44800. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44801. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44802. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44803. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44804. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44805. var index = _this._keys.indexOf(evt.keyCode);
  44806. if (index === -1) {
  44807. _this._keys.push(evt.keyCode);
  44808. }
  44809. if (!noPreventDefault) {
  44810. evt.preventDefault();
  44811. }
  44812. }
  44813. }
  44814. else {
  44815. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44816. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44817. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44818. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44819. var index = _this._keys.indexOf(evt.keyCode);
  44820. if (index >= 0) {
  44821. _this._keys.splice(index, 1);
  44822. }
  44823. if (!noPreventDefault) {
  44824. evt.preventDefault();
  44825. }
  44826. }
  44827. }
  44828. });
  44829. };
  44830. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44831. if (this._scene) {
  44832. if (this._onKeyboardObserver) {
  44833. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44834. }
  44835. if (this._onCanvasBlurObserver) {
  44836. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44837. }
  44838. this._onKeyboardObserver = null;
  44839. this._onCanvasBlurObserver = null;
  44840. }
  44841. this._keys = [];
  44842. };
  44843. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44844. if (this._onKeyboardObserver) {
  44845. var camera = this.camera;
  44846. // Keyboard
  44847. for (var index = 0; index < this._keys.length; index++) {
  44848. var keyCode = this._keys[index];
  44849. var speed = camera._computeLocalCameraSpeed();
  44850. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44851. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44852. }
  44853. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44854. camera._localDirection.copyFromFloats(0, 0, speed);
  44855. }
  44856. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44857. camera._localDirection.copyFromFloats(speed, 0, 0);
  44858. }
  44859. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44860. camera._localDirection.copyFromFloats(0, 0, -speed);
  44861. }
  44862. if (camera.getScene().useRightHandedSystem) {
  44863. camera._localDirection.z *= -1;
  44864. }
  44865. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44866. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44867. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44868. }
  44869. }
  44870. };
  44871. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44872. return "FreeCameraKeyboardMoveInput";
  44873. };
  44874. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44875. this._keys = [];
  44876. };
  44877. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44878. return "keyboard";
  44879. };
  44880. __decorate([
  44881. BABYLON.serialize()
  44882. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44883. __decorate([
  44884. BABYLON.serialize()
  44885. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44886. __decorate([
  44887. BABYLON.serialize()
  44888. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44889. __decorate([
  44890. BABYLON.serialize()
  44891. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44892. return FreeCameraKeyboardMoveInput;
  44893. }());
  44894. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44895. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44896. })(BABYLON || (BABYLON = {}));
  44897. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44898. "use strict";
  44899. var BABYLON;
  44900. (function (BABYLON) {
  44901. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44902. __extends(FreeCameraInputsManager, _super);
  44903. function FreeCameraInputsManager(camera) {
  44904. return _super.call(this, camera) || this;
  44905. }
  44906. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44907. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44908. return this;
  44909. };
  44910. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44911. if (touchEnabled === void 0) { touchEnabled = true; }
  44912. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44913. return this;
  44914. };
  44915. FreeCameraInputsManager.prototype.addGamepad = function () {
  44916. this.add(new BABYLON.FreeCameraGamepadInput());
  44917. return this;
  44918. };
  44919. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44920. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44921. return this;
  44922. };
  44923. FreeCameraInputsManager.prototype.addTouch = function () {
  44924. this.add(new BABYLON.FreeCameraTouchInput());
  44925. return this;
  44926. };
  44927. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44928. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44929. return this;
  44930. };
  44931. return FreeCameraInputsManager;
  44932. }(BABYLON.CameraInputsManager));
  44933. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44934. })(BABYLON || (BABYLON = {}));
  44935. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44936. "use strict";
  44937. var BABYLON;
  44938. (function (BABYLON) {
  44939. var FreeCamera = /** @class */ (function (_super) {
  44940. __extends(FreeCamera, _super);
  44941. function FreeCamera(name, position, scene) {
  44942. var _this = _super.call(this, name, position, scene) || this;
  44943. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44944. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44945. _this.checkCollisions = false;
  44946. _this.applyGravity = false;
  44947. _this._needMoveForGravity = false;
  44948. _this._oldPosition = BABYLON.Vector3.Zero();
  44949. _this._diffPosition = BABYLON.Vector3.Zero();
  44950. _this._newPosition = BABYLON.Vector3.Zero();
  44951. // Collisions
  44952. _this._collisionMask = -1;
  44953. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44954. if (collidedMesh === void 0) { collidedMesh = null; }
  44955. //TODO move this to the collision coordinator!
  44956. if (_this.getScene().workerCollisions)
  44957. newPosition.multiplyInPlace(_this._collider._radius);
  44958. var updatePosition = function (newPos) {
  44959. _this._newPosition.copyFrom(newPos);
  44960. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44961. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44962. _this.position.addInPlace(_this._diffPosition);
  44963. if (_this.onCollide && collidedMesh) {
  44964. _this.onCollide(collidedMesh);
  44965. }
  44966. }
  44967. };
  44968. updatePosition(newPosition);
  44969. };
  44970. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44971. _this.inputs.addKeyboard().addMouse();
  44972. return _this;
  44973. }
  44974. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44975. //-- begin properties for backward compatibility for inputs
  44976. /**
  44977. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44978. * Higher values reduce sensitivity.
  44979. */
  44980. get: function () {
  44981. var mouse = this.inputs.attached["mouse"];
  44982. if (mouse)
  44983. return mouse.angularSensibility;
  44984. return 0;
  44985. },
  44986. /**
  44987. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44988. * Higher values reduce sensitivity.
  44989. */
  44990. set: function (value) {
  44991. var mouse = this.inputs.attached["mouse"];
  44992. if (mouse)
  44993. mouse.angularSensibility = value;
  44994. },
  44995. enumerable: true,
  44996. configurable: true
  44997. });
  44998. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44999. get: function () {
  45000. var keyboard = this.inputs.attached["keyboard"];
  45001. if (keyboard)
  45002. return keyboard.keysUp;
  45003. return [];
  45004. },
  45005. set: function (value) {
  45006. var keyboard = this.inputs.attached["keyboard"];
  45007. if (keyboard)
  45008. keyboard.keysUp = value;
  45009. },
  45010. enumerable: true,
  45011. configurable: true
  45012. });
  45013. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  45014. get: function () {
  45015. var keyboard = this.inputs.attached["keyboard"];
  45016. if (keyboard)
  45017. return keyboard.keysDown;
  45018. return [];
  45019. },
  45020. set: function (value) {
  45021. var keyboard = this.inputs.attached["keyboard"];
  45022. if (keyboard)
  45023. keyboard.keysDown = value;
  45024. },
  45025. enumerable: true,
  45026. configurable: true
  45027. });
  45028. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  45029. get: function () {
  45030. var keyboard = this.inputs.attached["keyboard"];
  45031. if (keyboard)
  45032. return keyboard.keysLeft;
  45033. return [];
  45034. },
  45035. set: function (value) {
  45036. var keyboard = this.inputs.attached["keyboard"];
  45037. if (keyboard)
  45038. keyboard.keysLeft = value;
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  45044. get: function () {
  45045. var keyboard = this.inputs.attached["keyboard"];
  45046. if (keyboard)
  45047. return keyboard.keysRight;
  45048. return [];
  45049. },
  45050. set: function (value) {
  45051. var keyboard = this.inputs.attached["keyboard"];
  45052. if (keyboard)
  45053. keyboard.keysRight = value;
  45054. },
  45055. enumerable: true,
  45056. configurable: true
  45057. });
  45058. // Controls
  45059. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45060. this.inputs.attachElement(element, noPreventDefault);
  45061. };
  45062. FreeCamera.prototype.detachControl = function (element) {
  45063. this.inputs.detachElement(element);
  45064. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  45065. this.cameraRotation = new BABYLON.Vector2(0, 0);
  45066. };
  45067. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  45068. get: function () {
  45069. return this._collisionMask;
  45070. },
  45071. set: function (mask) {
  45072. this._collisionMask = !isNaN(mask) ? mask : -1;
  45073. },
  45074. enumerable: true,
  45075. configurable: true
  45076. });
  45077. FreeCamera.prototype._collideWithWorld = function (displacement) {
  45078. var globalPosition;
  45079. if (this.parent) {
  45080. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  45081. }
  45082. else {
  45083. globalPosition = this.position;
  45084. }
  45085. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  45086. this._oldPosition.addInPlace(this.ellipsoidOffset);
  45087. if (!this._collider) {
  45088. this._collider = new BABYLON.Collider();
  45089. }
  45090. this._collider._radius = this.ellipsoid;
  45091. this._collider.collisionMask = this._collisionMask;
  45092. //no need for clone, as long as gravity is not on.
  45093. var actualDisplacement = displacement;
  45094. //add gravity to the direction to prevent the dual-collision checking
  45095. if (this.applyGravity) {
  45096. //this prevents mending with cameraDirection, a global variable of the free camera class.
  45097. actualDisplacement = displacement.add(this.getScene().gravity);
  45098. }
  45099. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45100. };
  45101. FreeCamera.prototype._checkInputs = function () {
  45102. if (!this._localDirection) {
  45103. this._localDirection = BABYLON.Vector3.Zero();
  45104. this._transformedDirection = BABYLON.Vector3.Zero();
  45105. }
  45106. this.inputs.checkInputs();
  45107. _super.prototype._checkInputs.call(this);
  45108. };
  45109. FreeCamera.prototype._decideIfNeedsToMove = function () {
  45110. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  45111. };
  45112. FreeCamera.prototype._updatePosition = function () {
  45113. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  45114. this._collideWithWorld(this.cameraDirection);
  45115. }
  45116. else {
  45117. _super.prototype._updatePosition.call(this);
  45118. }
  45119. };
  45120. FreeCamera.prototype.dispose = function () {
  45121. this.inputs.clear();
  45122. _super.prototype.dispose.call(this);
  45123. };
  45124. FreeCamera.prototype.getClassName = function () {
  45125. return "FreeCamera";
  45126. };
  45127. __decorate([
  45128. BABYLON.serializeAsVector3()
  45129. ], FreeCamera.prototype, "ellipsoid", void 0);
  45130. __decorate([
  45131. BABYLON.serializeAsVector3()
  45132. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  45133. __decorate([
  45134. BABYLON.serialize()
  45135. ], FreeCamera.prototype, "checkCollisions", void 0);
  45136. __decorate([
  45137. BABYLON.serialize()
  45138. ], FreeCamera.prototype, "applyGravity", void 0);
  45139. return FreeCamera;
  45140. }(BABYLON.TargetCamera));
  45141. BABYLON.FreeCamera = FreeCamera;
  45142. })(BABYLON || (BABYLON = {}));
  45143. //# sourceMappingURL=babylon.freeCamera.js.map
  45144. "use strict";
  45145. var BABYLON;
  45146. (function (BABYLON) {
  45147. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  45148. function ArcRotateCameraKeyboardMoveInput() {
  45149. this._keys = new Array();
  45150. this.keysUp = [38];
  45151. this.keysDown = [40];
  45152. this.keysLeft = [37];
  45153. this.keysRight = [39];
  45154. this.keysReset = [220];
  45155. this.panningSensibility = 50.0;
  45156. this.zoomingSensibility = 25.0;
  45157. this.useAltToZoom = true;
  45158. }
  45159. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  45160. var _this = this;
  45161. if (this._onCanvasBlurObserver) {
  45162. return;
  45163. }
  45164. this._scene = this.camera.getScene();
  45165. this._engine = this._scene.getEngine();
  45166. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  45167. _this._keys = [];
  45168. });
  45169. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  45170. var evt = info.event;
  45171. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  45172. _this._ctrlPressed = evt.ctrlKey;
  45173. _this._altPressed = evt.altKey;
  45174. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  45175. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  45176. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  45177. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  45178. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  45179. var index = _this._keys.indexOf(evt.keyCode);
  45180. if (index === -1) {
  45181. _this._keys.push(evt.keyCode);
  45182. }
  45183. if (evt.preventDefault) {
  45184. if (!noPreventDefault) {
  45185. evt.preventDefault();
  45186. }
  45187. }
  45188. }
  45189. }
  45190. else {
  45191. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  45192. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  45193. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  45194. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  45195. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  45196. var index = _this._keys.indexOf(evt.keyCode);
  45197. if (index >= 0) {
  45198. _this._keys.splice(index, 1);
  45199. }
  45200. if (evt.preventDefault) {
  45201. if (!noPreventDefault) {
  45202. evt.preventDefault();
  45203. }
  45204. }
  45205. }
  45206. }
  45207. });
  45208. };
  45209. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  45210. if (this._scene) {
  45211. if (this._onKeyboardObserver) {
  45212. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  45213. }
  45214. if (this._onCanvasBlurObserver) {
  45215. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  45216. }
  45217. this._onKeyboardObserver = null;
  45218. this._onCanvasBlurObserver = null;
  45219. }
  45220. this._keys = [];
  45221. };
  45222. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  45223. if (this._onKeyboardObserver) {
  45224. var camera = this.camera;
  45225. for (var index = 0; index < this._keys.length; index++) {
  45226. var keyCode = this._keys[index];
  45227. if (this.keysLeft.indexOf(keyCode) !== -1) {
  45228. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45229. camera.inertialPanningX -= 1 / this.panningSensibility;
  45230. }
  45231. else {
  45232. camera.inertialAlphaOffset -= 0.01;
  45233. }
  45234. }
  45235. else if (this.keysUp.indexOf(keyCode) !== -1) {
  45236. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45237. camera.inertialPanningY += 1 / this.panningSensibility;
  45238. }
  45239. else if (this._altPressed && this.useAltToZoom) {
  45240. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  45241. }
  45242. else {
  45243. camera.inertialBetaOffset -= 0.01;
  45244. }
  45245. }
  45246. else if (this.keysRight.indexOf(keyCode) !== -1) {
  45247. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45248. camera.inertialPanningX += 1 / this.panningSensibility;
  45249. }
  45250. else {
  45251. camera.inertialAlphaOffset += 0.01;
  45252. }
  45253. }
  45254. else if (this.keysDown.indexOf(keyCode) !== -1) {
  45255. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  45256. camera.inertialPanningY -= 1 / this.panningSensibility;
  45257. }
  45258. else if (this._altPressed && this.useAltToZoom) {
  45259. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  45260. }
  45261. else {
  45262. camera.inertialBetaOffset += 0.01;
  45263. }
  45264. }
  45265. else if (this.keysReset.indexOf(keyCode) !== -1) {
  45266. camera.restoreState();
  45267. }
  45268. }
  45269. }
  45270. };
  45271. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  45272. return "ArcRotateCameraKeyboardMoveInput";
  45273. };
  45274. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  45275. return "keyboard";
  45276. };
  45277. __decorate([
  45278. BABYLON.serialize()
  45279. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  45280. __decorate([
  45281. BABYLON.serialize()
  45282. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  45283. __decorate([
  45284. BABYLON.serialize()
  45285. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  45286. __decorate([
  45287. BABYLON.serialize()
  45288. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  45289. __decorate([
  45290. BABYLON.serialize()
  45291. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  45292. __decorate([
  45293. BABYLON.serialize()
  45294. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  45295. __decorate([
  45296. BABYLON.serialize()
  45297. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  45298. __decorate([
  45299. BABYLON.serialize()
  45300. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  45301. return ArcRotateCameraKeyboardMoveInput;
  45302. }());
  45303. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  45304. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  45305. })(BABYLON || (BABYLON = {}));
  45306. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  45307. "use strict";
  45308. var BABYLON;
  45309. (function (BABYLON) {
  45310. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  45311. function ArcRotateCameraMouseWheelInput() {
  45312. this.wheelPrecision = 3.0;
  45313. /**
  45314. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  45315. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  45316. */
  45317. this.wheelDeltaPercentage = 0;
  45318. }
  45319. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  45320. var _this = this;
  45321. this._wheel = function (p, s) {
  45322. //sanity check - this should be a PointerWheel event.
  45323. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  45324. return;
  45325. var event = p.event;
  45326. var delta = 0;
  45327. if (event.wheelDelta) {
  45328. if (_this.wheelDeltaPercentage) {
  45329. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  45330. if (event.wheelDelta > 0) {
  45331. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  45332. }
  45333. else {
  45334. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  45335. }
  45336. }
  45337. else {
  45338. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  45339. }
  45340. }
  45341. else if (event.detail) {
  45342. delta = -event.detail / _this.wheelPrecision;
  45343. }
  45344. if (delta)
  45345. _this.camera.inertialRadiusOffset += delta;
  45346. if (event.preventDefault) {
  45347. if (!noPreventDefault) {
  45348. event.preventDefault();
  45349. }
  45350. }
  45351. };
  45352. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  45353. };
  45354. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  45355. if (this._observer && element) {
  45356. this.camera.getScene().onPointerObservable.remove(this._observer);
  45357. this._observer = null;
  45358. this._wheel = null;
  45359. }
  45360. };
  45361. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  45362. return "ArcRotateCameraMouseWheelInput";
  45363. };
  45364. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  45365. return "mousewheel";
  45366. };
  45367. __decorate([
  45368. BABYLON.serialize()
  45369. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  45370. __decorate([
  45371. BABYLON.serialize()
  45372. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  45373. return ArcRotateCameraMouseWheelInput;
  45374. }());
  45375. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  45376. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  45377. })(BABYLON || (BABYLON = {}));
  45378. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  45379. "use strict";
  45380. var BABYLON;
  45381. (function (BABYLON) {
  45382. var ArcRotateCameraPointersInput = /** @class */ (function () {
  45383. function ArcRotateCameraPointersInput() {
  45384. this.buttons = [0, 1, 2];
  45385. this.angularSensibilityX = 1000.0;
  45386. this.angularSensibilityY = 1000.0;
  45387. this.pinchPrecision = 12.0;
  45388. /**
  45389. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  45390. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  45391. */
  45392. this.pinchDeltaPercentage = 0;
  45393. this.panningSensibility = 1000.0;
  45394. this.multiTouchPanning = true;
  45395. this.multiTouchPanAndZoom = true;
  45396. this._isPanClick = false;
  45397. this.pinchInwards = true;
  45398. }
  45399. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  45400. var _this = this;
  45401. var engine = this.camera.getEngine();
  45402. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  45403. var pointA = null;
  45404. var pointB = null;
  45405. var previousPinchSquaredDistance = 0;
  45406. var initialDistance = 0;
  45407. var twoFingerActivityCount = 0;
  45408. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  45409. this._pointerInput = function (p, s) {
  45410. var evt = p.event;
  45411. var isTouch = p.event.pointerType === "touch";
  45412. if (engine.isInVRExclusivePointerMode) {
  45413. return;
  45414. }
  45415. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  45416. return;
  45417. }
  45418. var srcElement = (evt.srcElement || evt.target);
  45419. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  45420. try {
  45421. srcElement.setPointerCapture(evt.pointerId);
  45422. }
  45423. catch (e) {
  45424. //Nothing to do with the error. Execution will continue.
  45425. }
  45426. // Manage panning with pan button click
  45427. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  45428. // manage pointers
  45429. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  45430. if (pointA === null) {
  45431. pointA = cacheSoloPointer;
  45432. }
  45433. else if (pointB === null) {
  45434. pointB = cacheSoloPointer;
  45435. }
  45436. if (!noPreventDefault) {
  45437. evt.preventDefault();
  45438. element.focus();
  45439. }
  45440. }
  45441. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  45442. _this.camera.restoreState();
  45443. }
  45444. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  45445. try {
  45446. srcElement.releasePointerCapture(evt.pointerId);
  45447. }
  45448. catch (e) {
  45449. //Nothing to do with the error.
  45450. }
  45451. cacheSoloPointer = null;
  45452. previousPinchSquaredDistance = 0;
  45453. previousMultiTouchPanPosition.isPaning = false;
  45454. previousMultiTouchPanPosition.isPinching = false;
  45455. twoFingerActivityCount = 0;
  45456. initialDistance = 0;
  45457. if (!isTouch) {
  45458. pointB = null; // Mouse and pen are mono pointer
  45459. }
  45460. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  45461. //but emptying completly pointers collection is required to fix a bug on iPhone :
  45462. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  45463. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  45464. if (engine.badOS) {
  45465. pointA = pointB = null;
  45466. }
  45467. else {
  45468. //only remove the impacted pointer in case of multitouch allowing on most
  45469. //platforms switching from rotate to zoom and pan seamlessly.
  45470. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  45471. pointA = pointB;
  45472. pointB = null;
  45473. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  45474. }
  45475. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  45476. pointB = null;
  45477. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  45478. }
  45479. else {
  45480. pointA = pointB = null;
  45481. }
  45482. }
  45483. if (!noPreventDefault) {
  45484. evt.preventDefault();
  45485. }
  45486. }
  45487. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  45488. if (!noPreventDefault) {
  45489. evt.preventDefault();
  45490. }
  45491. // One button down
  45492. if (pointA && pointB === null && cacheSoloPointer) {
  45493. if (_this.panningSensibility !== 0 &&
  45494. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  45495. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  45496. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  45497. }
  45498. else {
  45499. var offsetX = evt.clientX - cacheSoloPointer.x;
  45500. var offsetY = evt.clientY - cacheSoloPointer.y;
  45501. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  45502. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  45503. }
  45504. cacheSoloPointer.x = evt.clientX;
  45505. cacheSoloPointer.y = evt.clientY;
  45506. }
  45507. else if (pointA && pointB) {
  45508. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  45509. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  45510. ed.x = evt.clientX;
  45511. ed.y = evt.clientY;
  45512. var direction = _this.pinchInwards ? 1 : -1;
  45513. var distX = pointA.x - pointB.x;
  45514. var distY = pointA.y - pointB.y;
  45515. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  45516. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  45517. if (previousPinchSquaredDistance === 0) {
  45518. initialDistance = pinchDistance;
  45519. previousPinchSquaredDistance = pinchSquaredDistance;
  45520. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  45521. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  45522. return;
  45523. }
  45524. if (_this.multiTouchPanAndZoom) {
  45525. if (_this.pinchDeltaPercentage) {
  45526. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  45527. }
  45528. else {
  45529. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  45530. (_this.pinchPrecision *
  45531. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  45532. direction);
  45533. }
  45534. if (_this.panningSensibility !== 0) {
  45535. var pointersCenterX = (pointA.x + pointB.x) / 2;
  45536. var pointersCenterY = (pointA.y + pointB.y) / 2;
  45537. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  45538. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  45539. previousMultiTouchPanPosition.x = pointersCenterX;
  45540. previousMultiTouchPanPosition.y = pointersCenterY;
  45541. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  45542. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  45543. }
  45544. }
  45545. else {
  45546. twoFingerActivityCount++;
  45547. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  45548. if (_this.pinchDeltaPercentage) {
  45549. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  45550. }
  45551. else {
  45552. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  45553. (_this.pinchPrecision *
  45554. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  45555. direction);
  45556. }
  45557. previousMultiTouchPanPosition.isPaning = false;
  45558. previousMultiTouchPanPosition.isPinching = true;
  45559. }
  45560. else {
  45561. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  45562. if (!previousMultiTouchPanPosition.isPaning) {
  45563. previousMultiTouchPanPosition.isPaning = true;
  45564. previousMultiTouchPanPosition.isPinching = false;
  45565. previousMultiTouchPanPosition.x = ed.x;
  45566. previousMultiTouchPanPosition.y = ed.y;
  45567. return;
  45568. }
  45569. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  45570. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  45571. }
  45572. }
  45573. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  45574. previousMultiTouchPanPosition.x = ed.x;
  45575. previousMultiTouchPanPosition.y = ed.y;
  45576. }
  45577. }
  45578. previousPinchSquaredDistance = pinchSquaredDistance;
  45579. }
  45580. }
  45581. };
  45582. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  45583. this._onContextMenu = function (evt) {
  45584. evt.preventDefault();
  45585. };
  45586. if (!this.camera._useCtrlForPanning) {
  45587. element.addEventListener("contextmenu", this._onContextMenu, false);
  45588. }
  45589. this._onLostFocus = function () {
  45590. //this._keys = [];
  45591. pointA = pointB = null;
  45592. previousPinchSquaredDistance = 0;
  45593. previousMultiTouchPanPosition.isPaning = false;
  45594. previousMultiTouchPanPosition.isPinching = false;
  45595. twoFingerActivityCount = 0;
  45596. cacheSoloPointer = null;
  45597. initialDistance = 0;
  45598. };
  45599. this._onMouseMove = function (evt) {
  45600. if (!engine.isPointerLock) {
  45601. return;
  45602. }
  45603. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  45604. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  45605. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  45606. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  45607. if (!noPreventDefault) {
  45608. evt.preventDefault();
  45609. }
  45610. };
  45611. this._onGestureStart = function (e) {
  45612. if (window.MSGesture === undefined) {
  45613. return;
  45614. }
  45615. if (!_this._MSGestureHandler) {
  45616. _this._MSGestureHandler = new MSGesture();
  45617. _this._MSGestureHandler.target = element;
  45618. }
  45619. _this._MSGestureHandler.addPointer(e.pointerId);
  45620. };
  45621. this._onGesture = function (e) {
  45622. _this.camera.radius *= e.scale;
  45623. if (e.preventDefault) {
  45624. if (!noPreventDefault) {
  45625. e.stopPropagation();
  45626. e.preventDefault();
  45627. }
  45628. }
  45629. };
  45630. element.addEventListener("mousemove", this._onMouseMove, false);
  45631. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  45632. element.addEventListener("MSGestureChange", this._onGesture, false);
  45633. BABYLON.Tools.RegisterTopRootEvents([
  45634. { name: "blur", handler: this._onLostFocus }
  45635. ]);
  45636. };
  45637. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  45638. if (this._onLostFocus) {
  45639. BABYLON.Tools.UnregisterTopRootEvents([
  45640. { name: "blur", handler: this._onLostFocus }
  45641. ]);
  45642. }
  45643. if (element && this._observer) {
  45644. this.camera.getScene().onPointerObservable.remove(this._observer);
  45645. this._observer = null;
  45646. if (this._onContextMenu) {
  45647. element.removeEventListener("contextmenu", this._onContextMenu);
  45648. }
  45649. if (this._onMouseMove) {
  45650. element.removeEventListener("mousemove", this._onMouseMove);
  45651. }
  45652. if (this._onGestureStart) {
  45653. element.removeEventListener("MSPointerDown", this._onGestureStart);
  45654. }
  45655. if (this._onGesture) {
  45656. element.removeEventListener("MSGestureChange", this._onGesture);
  45657. }
  45658. this._isPanClick = false;
  45659. this.pinchInwards = true;
  45660. this._onMouseMove = null;
  45661. this._onGestureStart = null;
  45662. this._onGesture = null;
  45663. this._MSGestureHandler = null;
  45664. this._onLostFocus = null;
  45665. this._onContextMenu = null;
  45666. }
  45667. };
  45668. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  45669. return "ArcRotateCameraPointersInput";
  45670. };
  45671. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  45672. return "pointers";
  45673. };
  45674. __decorate([
  45675. BABYLON.serialize()
  45676. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  45677. __decorate([
  45678. BABYLON.serialize()
  45679. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  45680. __decorate([
  45681. BABYLON.serialize()
  45682. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  45683. __decorate([
  45684. BABYLON.serialize()
  45685. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  45686. __decorate([
  45687. BABYLON.serialize()
  45688. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  45689. __decorate([
  45690. BABYLON.serialize()
  45691. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  45692. __decorate([
  45693. BABYLON.serialize()
  45694. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  45695. __decorate([
  45696. BABYLON.serialize()
  45697. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  45698. return ArcRotateCameraPointersInput;
  45699. }());
  45700. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  45701. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  45702. })(BABYLON || (BABYLON = {}));
  45703. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  45704. "use strict";
  45705. var BABYLON;
  45706. (function (BABYLON) {
  45707. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  45708. __extends(ArcRotateCameraInputsManager, _super);
  45709. function ArcRotateCameraInputsManager(camera) {
  45710. return _super.call(this, camera) || this;
  45711. }
  45712. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  45713. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  45714. return this;
  45715. };
  45716. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  45717. this.add(new BABYLON.ArcRotateCameraPointersInput());
  45718. return this;
  45719. };
  45720. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  45721. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  45722. return this;
  45723. };
  45724. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  45725. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  45726. return this;
  45727. };
  45728. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  45729. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  45730. return this;
  45731. };
  45732. return ArcRotateCameraInputsManager;
  45733. }(BABYLON.CameraInputsManager));
  45734. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  45735. })(BABYLON || (BABYLON = {}));
  45736. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  45737. "use strict";
  45738. var BABYLON;
  45739. (function (BABYLON) {
  45740. var ArcRotateCamera = /** @class */ (function (_super) {
  45741. __extends(ArcRotateCamera, _super);
  45742. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  45743. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  45744. _this.inertialAlphaOffset = 0;
  45745. _this.inertialBetaOffset = 0;
  45746. _this.inertialRadiusOffset = 0;
  45747. _this.lowerAlphaLimit = null;
  45748. _this.upperAlphaLimit = null;
  45749. _this.lowerBetaLimit = 0.01;
  45750. _this.upperBetaLimit = Math.PI;
  45751. _this.lowerRadiusLimit = null;
  45752. _this.upperRadiusLimit = null;
  45753. _this.inertialPanningX = 0;
  45754. _this.inertialPanningY = 0;
  45755. _this.pinchToPanMaxDistance = 20;
  45756. _this.panningDistanceLimit = null;
  45757. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  45758. _this.panningInertia = 0.9;
  45759. //-- end properties for backward compatibility for inputs
  45760. _this.zoomOnFactor = 1;
  45761. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45762. _this.allowUpsideDown = true;
  45763. _this._viewMatrix = new BABYLON.Matrix();
  45764. // Panning
  45765. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45766. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45767. _this.checkCollisions = false;
  45768. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45769. _this._previousPosition = BABYLON.Vector3.Zero();
  45770. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45771. _this._newPosition = BABYLON.Vector3.Zero();
  45772. _this._computationVector = BABYLON.Vector3.Zero();
  45773. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45774. if (collidedMesh === void 0) { collidedMesh = null; }
  45775. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45776. newPosition.multiplyInPlace(_this._collider._radius);
  45777. }
  45778. if (!collidedMesh) {
  45779. _this._previousPosition.copyFrom(_this.position);
  45780. }
  45781. else {
  45782. _this.setPosition(newPosition);
  45783. if (_this.onCollide) {
  45784. _this.onCollide(collidedMesh);
  45785. }
  45786. }
  45787. // Recompute because of constraints
  45788. var cosa = Math.cos(_this.alpha);
  45789. var sina = Math.sin(_this.alpha);
  45790. var cosb = Math.cos(_this.beta);
  45791. var sinb = Math.sin(_this.beta);
  45792. if (sinb === 0) {
  45793. sinb = 0.0001;
  45794. }
  45795. var target = _this._getTargetPosition();
  45796. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45797. target.addToRef(_this._computationVector, _this._newPosition);
  45798. _this.position.copyFrom(_this._newPosition);
  45799. var up = _this.upVector;
  45800. if (_this.allowUpsideDown && _this.beta < 0) {
  45801. up = up.clone();
  45802. up = up.negate();
  45803. }
  45804. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45805. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45806. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45807. _this._collisionTriggered = false;
  45808. };
  45809. _this._target = BABYLON.Vector3.Zero();
  45810. if (target) {
  45811. _this.setTarget(target);
  45812. }
  45813. _this.alpha = alpha;
  45814. _this.beta = beta;
  45815. _this.radius = radius;
  45816. _this.getViewMatrix();
  45817. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45818. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45819. return _this;
  45820. }
  45821. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45822. get: function () {
  45823. return this._target;
  45824. },
  45825. set: function (value) {
  45826. this.setTarget(value);
  45827. },
  45828. enumerable: true,
  45829. configurable: true
  45830. });
  45831. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45832. //-- begin properties for backward compatibility for inputs
  45833. get: function () {
  45834. var pointers = this.inputs.attached["pointers"];
  45835. if (pointers)
  45836. return pointers.angularSensibilityX;
  45837. return 0;
  45838. },
  45839. set: function (value) {
  45840. var pointers = this.inputs.attached["pointers"];
  45841. if (pointers) {
  45842. pointers.angularSensibilityX = value;
  45843. }
  45844. },
  45845. enumerable: true,
  45846. configurable: true
  45847. });
  45848. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45849. get: function () {
  45850. var pointers = this.inputs.attached["pointers"];
  45851. if (pointers)
  45852. return pointers.angularSensibilityY;
  45853. return 0;
  45854. },
  45855. set: function (value) {
  45856. var pointers = this.inputs.attached["pointers"];
  45857. if (pointers) {
  45858. pointers.angularSensibilityY = value;
  45859. }
  45860. },
  45861. enumerable: true,
  45862. configurable: true
  45863. });
  45864. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45865. get: function () {
  45866. var pointers = this.inputs.attached["pointers"];
  45867. if (pointers)
  45868. return pointers.pinchPrecision;
  45869. return 0;
  45870. },
  45871. set: function (value) {
  45872. var pointers = this.inputs.attached["pointers"];
  45873. if (pointers) {
  45874. pointers.pinchPrecision = value;
  45875. }
  45876. },
  45877. enumerable: true,
  45878. configurable: true
  45879. });
  45880. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45881. get: function () {
  45882. var pointers = this.inputs.attached["pointers"];
  45883. if (pointers)
  45884. return pointers.pinchDeltaPercentage;
  45885. return 0;
  45886. },
  45887. set: function (value) {
  45888. var pointers = this.inputs.attached["pointers"];
  45889. if (pointers) {
  45890. pointers.pinchDeltaPercentage = value;
  45891. }
  45892. },
  45893. enumerable: true,
  45894. configurable: true
  45895. });
  45896. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45897. get: function () {
  45898. var pointers = this.inputs.attached["pointers"];
  45899. if (pointers)
  45900. return pointers.panningSensibility;
  45901. return 0;
  45902. },
  45903. set: function (value) {
  45904. var pointers = this.inputs.attached["pointers"];
  45905. if (pointers) {
  45906. pointers.panningSensibility = value;
  45907. }
  45908. },
  45909. enumerable: true,
  45910. configurable: true
  45911. });
  45912. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45913. get: function () {
  45914. var keyboard = this.inputs.attached["keyboard"];
  45915. if (keyboard)
  45916. return keyboard.keysUp;
  45917. return [];
  45918. },
  45919. set: function (value) {
  45920. var keyboard = this.inputs.attached["keyboard"];
  45921. if (keyboard)
  45922. keyboard.keysUp = value;
  45923. },
  45924. enumerable: true,
  45925. configurable: true
  45926. });
  45927. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45928. get: function () {
  45929. var keyboard = this.inputs.attached["keyboard"];
  45930. if (keyboard)
  45931. return keyboard.keysDown;
  45932. return [];
  45933. },
  45934. set: function (value) {
  45935. var keyboard = this.inputs.attached["keyboard"];
  45936. if (keyboard)
  45937. keyboard.keysDown = value;
  45938. },
  45939. enumerable: true,
  45940. configurable: true
  45941. });
  45942. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45943. get: function () {
  45944. var keyboard = this.inputs.attached["keyboard"];
  45945. if (keyboard)
  45946. return keyboard.keysLeft;
  45947. return [];
  45948. },
  45949. set: function (value) {
  45950. var keyboard = this.inputs.attached["keyboard"];
  45951. if (keyboard)
  45952. keyboard.keysLeft = value;
  45953. },
  45954. enumerable: true,
  45955. configurable: true
  45956. });
  45957. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45958. get: function () {
  45959. var keyboard = this.inputs.attached["keyboard"];
  45960. if (keyboard)
  45961. return keyboard.keysRight;
  45962. return [];
  45963. },
  45964. set: function (value) {
  45965. var keyboard = this.inputs.attached["keyboard"];
  45966. if (keyboard)
  45967. keyboard.keysRight = value;
  45968. },
  45969. enumerable: true,
  45970. configurable: true
  45971. });
  45972. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45973. get: function () {
  45974. var mousewheel = this.inputs.attached["mousewheel"];
  45975. if (mousewheel)
  45976. return mousewheel.wheelPrecision;
  45977. return 0;
  45978. },
  45979. set: function (value) {
  45980. var mousewheel = this.inputs.attached["mousewheel"];
  45981. if (mousewheel)
  45982. mousewheel.wheelPrecision = value;
  45983. },
  45984. enumerable: true,
  45985. configurable: true
  45986. });
  45987. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45988. get: function () {
  45989. var mousewheel = this.inputs.attached["mousewheel"];
  45990. if (mousewheel)
  45991. return mousewheel.wheelDeltaPercentage;
  45992. return 0;
  45993. },
  45994. set: function (value) {
  45995. var mousewheel = this.inputs.attached["mousewheel"];
  45996. if (mousewheel)
  45997. mousewheel.wheelDeltaPercentage = value;
  45998. },
  45999. enumerable: true,
  46000. configurable: true
  46001. });
  46002. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  46003. get: function () {
  46004. return this._bouncingBehavior;
  46005. },
  46006. enumerable: true,
  46007. configurable: true
  46008. });
  46009. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  46010. get: function () {
  46011. return this._bouncingBehavior != null;
  46012. },
  46013. set: function (value) {
  46014. if (value === this.useBouncingBehavior) {
  46015. return;
  46016. }
  46017. if (value) {
  46018. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  46019. this.addBehavior(this._bouncingBehavior);
  46020. }
  46021. else if (this._bouncingBehavior) {
  46022. this.removeBehavior(this._bouncingBehavior);
  46023. this._bouncingBehavior = null;
  46024. }
  46025. },
  46026. enumerable: true,
  46027. configurable: true
  46028. });
  46029. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  46030. get: function () {
  46031. return this._framingBehavior;
  46032. },
  46033. enumerable: true,
  46034. configurable: true
  46035. });
  46036. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  46037. get: function () {
  46038. return this._framingBehavior != null;
  46039. },
  46040. set: function (value) {
  46041. if (value === this.useFramingBehavior) {
  46042. return;
  46043. }
  46044. if (value) {
  46045. this._framingBehavior = new BABYLON.FramingBehavior();
  46046. this.addBehavior(this._framingBehavior);
  46047. }
  46048. else if (this._framingBehavior) {
  46049. this.removeBehavior(this._framingBehavior);
  46050. this._framingBehavior = null;
  46051. }
  46052. },
  46053. enumerable: true,
  46054. configurable: true
  46055. });
  46056. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  46057. get: function () {
  46058. return this._autoRotationBehavior;
  46059. },
  46060. enumerable: true,
  46061. configurable: true
  46062. });
  46063. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  46064. get: function () {
  46065. return this._autoRotationBehavior != null;
  46066. },
  46067. set: function (value) {
  46068. if (value === this.useAutoRotationBehavior) {
  46069. return;
  46070. }
  46071. if (value) {
  46072. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  46073. this.addBehavior(this._autoRotationBehavior);
  46074. }
  46075. else if (this._autoRotationBehavior) {
  46076. this.removeBehavior(this._autoRotationBehavior);
  46077. this._autoRotationBehavior = null;
  46078. }
  46079. },
  46080. enumerable: true,
  46081. configurable: true
  46082. });
  46083. // Cache
  46084. ArcRotateCamera.prototype._initCache = function () {
  46085. _super.prototype._initCache.call(this);
  46086. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46087. this._cache.alpha = undefined;
  46088. this._cache.beta = undefined;
  46089. this._cache.radius = undefined;
  46090. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  46091. };
  46092. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  46093. if (!ignoreParentClass) {
  46094. _super.prototype._updateCache.call(this);
  46095. }
  46096. this._cache._target.copyFrom(this._getTargetPosition());
  46097. this._cache.alpha = this.alpha;
  46098. this._cache.beta = this.beta;
  46099. this._cache.radius = this.radius;
  46100. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  46101. };
  46102. ArcRotateCamera.prototype._getTargetPosition = function () {
  46103. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  46104. var pos = this._targetHost.getAbsolutePosition();
  46105. if (this._targetBoundingCenter) {
  46106. pos.addToRef(this._targetBoundingCenter, this._target);
  46107. }
  46108. else {
  46109. this._target.copyFrom(pos);
  46110. }
  46111. }
  46112. var lockedTargetPosition = this._getLockedTargetPosition();
  46113. if (lockedTargetPosition) {
  46114. return lockedTargetPosition;
  46115. }
  46116. return this._target;
  46117. };
  46118. ArcRotateCamera.prototype.storeState = function () {
  46119. this._storedAlpha = this.alpha;
  46120. this._storedBeta = this.beta;
  46121. this._storedRadius = this.radius;
  46122. this._storedTarget = this._getTargetPosition().clone();
  46123. return _super.prototype.storeState.call(this);
  46124. };
  46125. /**
  46126. * Restored camera state. You must call storeState() first
  46127. */
  46128. ArcRotateCamera.prototype._restoreStateValues = function () {
  46129. if (!_super.prototype._restoreStateValues.call(this)) {
  46130. return false;
  46131. }
  46132. this.alpha = this._storedAlpha;
  46133. this.beta = this._storedBeta;
  46134. this.radius = this._storedRadius;
  46135. this.setTarget(this._storedTarget.clone());
  46136. this.inertialAlphaOffset = 0;
  46137. this.inertialBetaOffset = 0;
  46138. this.inertialRadiusOffset = 0;
  46139. this.inertialPanningX = 0;
  46140. this.inertialPanningY = 0;
  46141. return true;
  46142. };
  46143. // Synchronized
  46144. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  46145. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  46146. return false;
  46147. return this._cache._target.equals(this._getTargetPosition())
  46148. && this._cache.alpha === this.alpha
  46149. && this._cache.beta === this.beta
  46150. && this._cache.radius === this.radius
  46151. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  46152. };
  46153. // Methods
  46154. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  46155. var _this = this;
  46156. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  46157. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  46158. this._useCtrlForPanning = useCtrlForPanning;
  46159. this._panningMouseButton = panningMouseButton;
  46160. this.inputs.attachElement(element, noPreventDefault);
  46161. this._reset = function () {
  46162. _this.inertialAlphaOffset = 0;
  46163. _this.inertialBetaOffset = 0;
  46164. _this.inertialRadiusOffset = 0;
  46165. _this.inertialPanningX = 0;
  46166. _this.inertialPanningY = 0;
  46167. };
  46168. };
  46169. ArcRotateCamera.prototype.detachControl = function (element) {
  46170. this.inputs.detachElement(element);
  46171. if (this._reset) {
  46172. this._reset();
  46173. }
  46174. };
  46175. ArcRotateCamera.prototype._checkInputs = function () {
  46176. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  46177. if (this._collisionTriggered) {
  46178. return;
  46179. }
  46180. this.inputs.checkInputs();
  46181. // Inertia
  46182. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  46183. if (this.getScene().useRightHandedSystem) {
  46184. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  46185. }
  46186. else {
  46187. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  46188. }
  46189. this.beta += this.inertialBetaOffset;
  46190. this.radius -= this.inertialRadiusOffset;
  46191. this.inertialAlphaOffset *= this.inertia;
  46192. this.inertialBetaOffset *= this.inertia;
  46193. this.inertialRadiusOffset *= this.inertia;
  46194. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  46195. this.inertialAlphaOffset = 0;
  46196. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  46197. this.inertialBetaOffset = 0;
  46198. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  46199. this.inertialRadiusOffset = 0;
  46200. }
  46201. // Panning inertia
  46202. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  46203. if (!this._localDirection) {
  46204. this._localDirection = BABYLON.Vector3.Zero();
  46205. this._transformedDirection = BABYLON.Vector3.Zero();
  46206. }
  46207. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  46208. this._localDirection.multiplyInPlace(this.panningAxis);
  46209. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  46210. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  46211. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  46212. if (!this.panningAxis.y) {
  46213. this._transformedDirection.y = 0;
  46214. }
  46215. if (!this._targetHost) {
  46216. if (this.panningDistanceLimit) {
  46217. this._transformedDirection.addInPlace(this._target);
  46218. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  46219. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  46220. this._target.copyFrom(this._transformedDirection);
  46221. }
  46222. }
  46223. else {
  46224. this._target.addInPlace(this._transformedDirection);
  46225. }
  46226. }
  46227. this.inertialPanningX *= this.panningInertia;
  46228. this.inertialPanningY *= this.panningInertia;
  46229. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  46230. this.inertialPanningX = 0;
  46231. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  46232. this.inertialPanningY = 0;
  46233. }
  46234. // Limits
  46235. this._checkLimits();
  46236. _super.prototype._checkInputs.call(this);
  46237. };
  46238. ArcRotateCamera.prototype._checkLimits = function () {
  46239. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  46240. if (this.allowUpsideDown && this.beta > Math.PI) {
  46241. this.beta = this.beta - (2 * Math.PI);
  46242. }
  46243. }
  46244. else {
  46245. if (this.beta < this.lowerBetaLimit) {
  46246. this.beta = this.lowerBetaLimit;
  46247. }
  46248. }
  46249. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  46250. if (this.allowUpsideDown && this.beta < -Math.PI) {
  46251. this.beta = this.beta + (2 * Math.PI);
  46252. }
  46253. }
  46254. else {
  46255. if (this.beta > this.upperBetaLimit) {
  46256. this.beta = this.upperBetaLimit;
  46257. }
  46258. }
  46259. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  46260. this.alpha = this.lowerAlphaLimit;
  46261. }
  46262. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  46263. this.alpha = this.upperAlphaLimit;
  46264. }
  46265. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  46266. this.radius = this.lowerRadiusLimit;
  46267. }
  46268. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  46269. this.radius = this.upperRadiusLimit;
  46270. }
  46271. };
  46272. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  46273. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  46274. this.radius = this._computationVector.length();
  46275. if (this.radius === 0) {
  46276. this.radius = 0.0001; // Just to avoid division by zero
  46277. }
  46278. // Alpha
  46279. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  46280. if (this._computationVector.z < 0) {
  46281. this.alpha = 2 * Math.PI - this.alpha;
  46282. }
  46283. // Beta
  46284. this.beta = Math.acos(this._computationVector.y / this.radius);
  46285. this._checkLimits();
  46286. };
  46287. ArcRotateCamera.prototype.setPosition = function (position) {
  46288. if (this.position.equals(position)) {
  46289. return;
  46290. }
  46291. this.position.copyFrom(position);
  46292. this.rebuildAnglesAndRadius();
  46293. };
  46294. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  46295. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  46296. if (allowSamePosition === void 0) { allowSamePosition = false; }
  46297. if (target.getBoundingInfo) {
  46298. if (toBoundingCenter) {
  46299. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  46300. }
  46301. else {
  46302. this._targetBoundingCenter = null;
  46303. }
  46304. this._targetHost = target;
  46305. this._target = this._getTargetPosition();
  46306. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  46307. }
  46308. else {
  46309. var newTarget = target;
  46310. var currentTarget = this._getTargetPosition();
  46311. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  46312. return;
  46313. }
  46314. this._targetHost = null;
  46315. this._target = newTarget;
  46316. this._targetBoundingCenter = null;
  46317. this.onMeshTargetChangedObservable.notifyObservers(null);
  46318. }
  46319. this.rebuildAnglesAndRadius();
  46320. };
  46321. ArcRotateCamera.prototype._getViewMatrix = function () {
  46322. // Compute
  46323. var cosa = Math.cos(this.alpha);
  46324. var sina = Math.sin(this.alpha);
  46325. var cosb = Math.cos(this.beta);
  46326. var sinb = Math.sin(this.beta);
  46327. if (sinb === 0) {
  46328. sinb = 0.0001;
  46329. }
  46330. var target = this._getTargetPosition();
  46331. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  46332. target.addToRef(this._computationVector, this._newPosition);
  46333. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  46334. if (!this._collider) {
  46335. this._collider = new BABYLON.Collider();
  46336. }
  46337. this._collider._radius = this.collisionRadius;
  46338. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  46339. this._collisionTriggered = true;
  46340. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46341. }
  46342. else {
  46343. this.position.copyFrom(this._newPosition);
  46344. var up = this.upVector;
  46345. if (this.allowUpsideDown && sinb < 0) {
  46346. up = up.clone();
  46347. up = up.negate();
  46348. }
  46349. if (this.getScene().useRightHandedSystem) {
  46350. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  46351. }
  46352. else {
  46353. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  46354. }
  46355. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  46356. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  46357. }
  46358. this._currentTarget = target;
  46359. return this._viewMatrix;
  46360. };
  46361. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  46362. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  46363. meshes = meshes || this.getScene().meshes;
  46364. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  46365. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  46366. this.radius = distance * this.zoomOnFactor;
  46367. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  46368. };
  46369. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  46370. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  46371. var meshesOrMinMaxVector;
  46372. var distance;
  46373. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  46374. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  46375. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  46376. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  46377. }
  46378. else {
  46379. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  46380. meshesOrMinMaxVector = minMaxVectorAndDistance;
  46381. distance = minMaxVectorAndDistance.distance;
  46382. }
  46383. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  46384. if (!doNotUpdateMaxZ) {
  46385. this.maxZ = distance * 2;
  46386. }
  46387. };
  46388. /**
  46389. * @override
  46390. * Override Camera.createRigCamera
  46391. */
  46392. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46393. var alphaShift = 0;
  46394. switch (this.cameraRigMode) {
  46395. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46396. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46397. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46398. case BABYLON.Camera.RIG_MODE_VR:
  46399. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  46400. break;
  46401. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46402. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  46403. break;
  46404. }
  46405. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  46406. rigCam._cameraRigParams = {};
  46407. return rigCam;
  46408. };
  46409. /**
  46410. * @override
  46411. * Override Camera._updateRigCameras
  46412. */
  46413. ArcRotateCamera.prototype._updateRigCameras = function () {
  46414. var camLeft = this._rigCameras[0];
  46415. var camRight = this._rigCameras[1];
  46416. camLeft.beta = camRight.beta = this.beta;
  46417. camLeft.radius = camRight.radius = this.radius;
  46418. switch (this.cameraRigMode) {
  46419. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46420. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46421. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46422. case BABYLON.Camera.RIG_MODE_VR:
  46423. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  46424. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  46425. break;
  46426. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46427. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  46428. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  46429. break;
  46430. }
  46431. _super.prototype._updateRigCameras.call(this);
  46432. };
  46433. ArcRotateCamera.prototype.dispose = function () {
  46434. this.inputs.clear();
  46435. _super.prototype.dispose.call(this);
  46436. };
  46437. ArcRotateCamera.prototype.getClassName = function () {
  46438. return "ArcRotateCamera";
  46439. };
  46440. __decorate([
  46441. BABYLON.serialize()
  46442. ], ArcRotateCamera.prototype, "alpha", void 0);
  46443. __decorate([
  46444. BABYLON.serialize()
  46445. ], ArcRotateCamera.prototype, "beta", void 0);
  46446. __decorate([
  46447. BABYLON.serialize()
  46448. ], ArcRotateCamera.prototype, "radius", void 0);
  46449. __decorate([
  46450. BABYLON.serializeAsVector3("target")
  46451. ], ArcRotateCamera.prototype, "_target", void 0);
  46452. __decorate([
  46453. BABYLON.serialize()
  46454. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  46455. __decorate([
  46456. BABYLON.serialize()
  46457. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  46458. __decorate([
  46459. BABYLON.serialize()
  46460. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  46461. __decorate([
  46462. BABYLON.serialize()
  46463. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  46464. __decorate([
  46465. BABYLON.serialize()
  46466. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  46467. __decorate([
  46468. BABYLON.serialize()
  46469. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  46470. __decorate([
  46471. BABYLON.serialize()
  46472. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  46473. __decorate([
  46474. BABYLON.serialize()
  46475. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  46476. __decorate([
  46477. BABYLON.serialize()
  46478. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  46479. __decorate([
  46480. BABYLON.serialize()
  46481. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  46482. __decorate([
  46483. BABYLON.serialize()
  46484. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  46485. __decorate([
  46486. BABYLON.serialize()
  46487. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  46488. __decorate([
  46489. BABYLON.serialize()
  46490. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  46491. __decorate([
  46492. BABYLON.serializeAsVector3()
  46493. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  46494. __decorate([
  46495. BABYLON.serialize()
  46496. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  46497. __decorate([
  46498. BABYLON.serialize()
  46499. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  46500. __decorate([
  46501. BABYLON.serialize()
  46502. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  46503. return ArcRotateCamera;
  46504. }(BABYLON.TargetCamera));
  46505. BABYLON.ArcRotateCamera = ArcRotateCamera;
  46506. })(BABYLON || (BABYLON = {}));
  46507. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  46508. "use strict";
  46509. var BABYLON;
  46510. (function (BABYLON) {
  46511. /**
  46512. * The HemisphericLight simulates the ambient environment light,
  46513. * so the passed direction is the light reflection direction, not the incoming direction.
  46514. */
  46515. var HemisphericLight = /** @class */ (function (_super) {
  46516. __extends(HemisphericLight, _super);
  46517. /**
  46518. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  46519. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  46520. * The HemisphericLight can't cast shadows.
  46521. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46522. * @param name The friendly name of the light
  46523. * @param direction The direction of the light reflection
  46524. * @param scene The scene the light belongs to
  46525. */
  46526. function HemisphericLight(name, direction, scene) {
  46527. var _this = _super.call(this, name, scene) || this;
  46528. /**
  46529. * The groundColor is the light in the opposite direction to the one specified during creation.
  46530. * 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.
  46531. */
  46532. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  46533. _this.direction = direction || BABYLON.Vector3.Up();
  46534. return _this;
  46535. }
  46536. HemisphericLight.prototype._buildUniformLayout = function () {
  46537. this._uniformBuffer.addUniform("vLightData", 4);
  46538. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46539. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46540. this._uniformBuffer.addUniform("vLightGround", 3);
  46541. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46542. this._uniformBuffer.addUniform("depthValues", 2);
  46543. this._uniformBuffer.create();
  46544. };
  46545. /**
  46546. * Returns the string "HemisphericLight".
  46547. * @return The class name
  46548. */
  46549. HemisphericLight.prototype.getClassName = function () {
  46550. return "HemisphericLight";
  46551. };
  46552. /**
  46553. * Sets the HemisphericLight direction towards the passed target (Vector3).
  46554. * Returns the updated direction.
  46555. * @param target The target the direction should point to
  46556. * @return The computed direction
  46557. */
  46558. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  46559. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  46560. return this.direction;
  46561. };
  46562. /**
  46563. * Returns the shadow generator associated to the light.
  46564. * @returns Always null for hemispheric lights because it does not support shadows.
  46565. */
  46566. HemisphericLight.prototype.getShadowGenerator = function () {
  46567. return null;
  46568. };
  46569. /**
  46570. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  46571. * @param effect The effect to update
  46572. * @param lightIndex The index of the light in the effect to update
  46573. * @returns The hemispheric light
  46574. */
  46575. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  46576. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46577. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  46578. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  46579. return this;
  46580. };
  46581. /**
  46582. * @ignore internal use only.
  46583. */
  46584. HemisphericLight.prototype._getWorldMatrix = function () {
  46585. if (!this._worldMatrix) {
  46586. this._worldMatrix = BABYLON.Matrix.Identity();
  46587. }
  46588. return this._worldMatrix;
  46589. };
  46590. /**
  46591. * Returns the integer 3.
  46592. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46593. */
  46594. HemisphericLight.prototype.getTypeID = function () {
  46595. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  46596. };
  46597. __decorate([
  46598. BABYLON.serializeAsColor3()
  46599. ], HemisphericLight.prototype, "groundColor", void 0);
  46600. __decorate([
  46601. BABYLON.serializeAsVector3()
  46602. ], HemisphericLight.prototype, "direction", void 0);
  46603. return HemisphericLight;
  46604. }(BABYLON.Light));
  46605. BABYLON.HemisphericLight = HemisphericLight;
  46606. })(BABYLON || (BABYLON = {}));
  46607. //# sourceMappingURL=babylon.hemisphericLight.js.map
  46608. "use strict";
  46609. var BABYLON;
  46610. (function (BABYLON) {
  46611. /**
  46612. * Base implementation IShadowLight
  46613. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  46614. */
  46615. var ShadowLight = /** @class */ (function (_super) {
  46616. __extends(ShadowLight, _super);
  46617. function ShadowLight() {
  46618. var _this = _super !== null && _super.apply(this, arguments) || this;
  46619. _this._needProjectionMatrixCompute = true;
  46620. return _this;
  46621. }
  46622. ShadowLight.prototype._setPosition = function (value) {
  46623. this._position = value;
  46624. };
  46625. Object.defineProperty(ShadowLight.prototype, "position", {
  46626. /**
  46627. * Sets the position the shadow will be casted from. Also use as the light position for both
  46628. * point and spot lights.
  46629. */
  46630. get: function () {
  46631. return this._position;
  46632. },
  46633. /**
  46634. * Sets the position the shadow will be casted from. Also use as the light position for both
  46635. * point and spot lights.
  46636. */
  46637. set: function (value) {
  46638. this._setPosition(value);
  46639. },
  46640. enumerable: true,
  46641. configurable: true
  46642. });
  46643. ShadowLight.prototype._setDirection = function (value) {
  46644. this._direction = value;
  46645. };
  46646. Object.defineProperty(ShadowLight.prototype, "direction", {
  46647. /**
  46648. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  46649. * Also use as the light direction on spot and directional lights.
  46650. */
  46651. get: function () {
  46652. return this._direction;
  46653. },
  46654. /**
  46655. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  46656. * Also use as the light direction on spot and directional lights.
  46657. */
  46658. set: function (value) {
  46659. this._setDirection(value);
  46660. },
  46661. enumerable: true,
  46662. configurable: true
  46663. });
  46664. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  46665. /**
  46666. * Gets the shadow projection clipping minimum z value.
  46667. */
  46668. get: function () {
  46669. return this._shadowMinZ;
  46670. },
  46671. /**
  46672. * Sets the shadow projection clipping minimum z value.
  46673. */
  46674. set: function (value) {
  46675. this._shadowMinZ = value;
  46676. this.forceProjectionMatrixCompute();
  46677. },
  46678. enumerable: true,
  46679. configurable: true
  46680. });
  46681. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  46682. /**
  46683. * Sets the shadow projection clipping maximum z value.
  46684. */
  46685. get: function () {
  46686. return this._shadowMaxZ;
  46687. },
  46688. /**
  46689. * Gets the shadow projection clipping maximum z value.
  46690. */
  46691. set: function (value) {
  46692. this._shadowMaxZ = value;
  46693. this.forceProjectionMatrixCompute();
  46694. },
  46695. enumerable: true,
  46696. configurable: true
  46697. });
  46698. /**
  46699. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  46700. * @returns true if the information has been computed, false if it does not need to (no parenting)
  46701. */
  46702. ShadowLight.prototype.computeTransformedInformation = function () {
  46703. if (this.parent && this.parent.getWorldMatrix) {
  46704. if (!this.transformedPosition) {
  46705. this.transformedPosition = BABYLON.Vector3.Zero();
  46706. }
  46707. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  46708. // In case the direction is present.
  46709. if (this.direction) {
  46710. if (!this.transformedDirection) {
  46711. this.transformedDirection = BABYLON.Vector3.Zero();
  46712. }
  46713. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  46714. }
  46715. return true;
  46716. }
  46717. return false;
  46718. };
  46719. /**
  46720. * Return the depth scale used for the shadow map.
  46721. * @returns the depth scale.
  46722. */
  46723. ShadowLight.prototype.getDepthScale = function () {
  46724. return 50.0;
  46725. };
  46726. /**
  46727. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  46728. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46729. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46730. */
  46731. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  46732. return this.transformedDirection ? this.transformedDirection : this.direction;
  46733. };
  46734. /**
  46735. * Returns the ShadowLight absolute position in the World.
  46736. * @returns the position vector in world space
  46737. */
  46738. ShadowLight.prototype.getAbsolutePosition = function () {
  46739. return this.transformedPosition ? this.transformedPosition : this.position;
  46740. };
  46741. /**
  46742. * Sets the ShadowLight direction toward the passed target.
  46743. * @param target The point tot target in local space
  46744. * @returns the updated ShadowLight direction
  46745. */
  46746. ShadowLight.prototype.setDirectionToTarget = function (target) {
  46747. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  46748. return this.direction;
  46749. };
  46750. /**
  46751. * Returns the light rotation in euler definition.
  46752. * @returns the x y z rotation in local space.
  46753. */
  46754. ShadowLight.prototype.getRotation = function () {
  46755. this.direction.normalize();
  46756. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  46757. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  46758. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46759. };
  46760. /**
  46761. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46762. * @returns true if a cube texture needs to be use
  46763. */
  46764. ShadowLight.prototype.needCube = function () {
  46765. return false;
  46766. };
  46767. /**
  46768. * Detects if the projection matrix requires to be recomputed this frame.
  46769. * @returns true if it requires to be recomputed otherwise, false.
  46770. */
  46771. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46772. return this._needProjectionMatrixCompute;
  46773. };
  46774. /**
  46775. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46776. */
  46777. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46778. this._needProjectionMatrixCompute = true;
  46779. };
  46780. /**
  46781. * Get the world matrix of the sahdow lights.
  46782. * @ignore Internal Use Only
  46783. */
  46784. ShadowLight.prototype._getWorldMatrix = function () {
  46785. if (!this._worldMatrix) {
  46786. this._worldMatrix = BABYLON.Matrix.Identity();
  46787. }
  46788. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46789. return this._worldMatrix;
  46790. };
  46791. /**
  46792. * Gets the minZ used for shadow according to both the scene and the light.
  46793. * @param activeCamera The camera we are returning the min for
  46794. * @returns the depth min z
  46795. */
  46796. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46797. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46798. };
  46799. /**
  46800. * Gets the maxZ used for shadow according to both the scene and the light.
  46801. * @param activeCamera The camera we are returning the max for
  46802. * @returns the depth max z
  46803. */
  46804. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46805. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46806. };
  46807. /**
  46808. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46809. * @param matrix The materix to updated with the projection information
  46810. * @param viewMatrix The transform matrix of the light
  46811. * @param renderList The list of mesh to render in the map
  46812. * @returns The current light
  46813. */
  46814. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46815. if (this.customProjectionMatrixBuilder) {
  46816. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46817. }
  46818. else {
  46819. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46820. }
  46821. return this;
  46822. };
  46823. __decorate([
  46824. BABYLON.serializeAsVector3()
  46825. ], ShadowLight.prototype, "position", null);
  46826. __decorate([
  46827. BABYLON.serializeAsVector3()
  46828. ], ShadowLight.prototype, "direction", null);
  46829. __decorate([
  46830. BABYLON.serialize()
  46831. ], ShadowLight.prototype, "shadowMinZ", null);
  46832. __decorate([
  46833. BABYLON.serialize()
  46834. ], ShadowLight.prototype, "shadowMaxZ", null);
  46835. return ShadowLight;
  46836. }(BABYLON.Light));
  46837. BABYLON.ShadowLight = ShadowLight;
  46838. })(BABYLON || (BABYLON = {}));
  46839. //# sourceMappingURL=babylon.shadowLight.js.map
  46840. "use strict";
  46841. var BABYLON;
  46842. (function (BABYLON) {
  46843. /**
  46844. * A point light is a light defined by an unique point in world space.
  46845. * The light is emitted in every direction from this point.
  46846. * A good example of a point light is a standard light bulb.
  46847. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46848. */
  46849. var PointLight = /** @class */ (function (_super) {
  46850. __extends(PointLight, _super);
  46851. /**
  46852. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46853. * A PointLight emits the light in every direction.
  46854. * It can cast shadows.
  46855. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46856. * ```javascript
  46857. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46858. * ```
  46859. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46860. * @param name The light friendly name
  46861. * @param position The position of the point light in the scene
  46862. * @param scene The scene the lights belongs to
  46863. */
  46864. function PointLight(name, position, scene) {
  46865. var _this = _super.call(this, name, scene) || this;
  46866. _this._shadowAngle = Math.PI / 2;
  46867. _this.position = position;
  46868. return _this;
  46869. }
  46870. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46871. /**
  46872. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46873. * This specifies what angle the shadow will use to be created.
  46874. *
  46875. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46876. */
  46877. get: function () {
  46878. return this._shadowAngle;
  46879. },
  46880. /**
  46881. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46882. * This specifies what angle the shadow will use to be created.
  46883. *
  46884. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46885. */
  46886. set: function (value) {
  46887. this._shadowAngle = value;
  46888. this.forceProjectionMatrixCompute();
  46889. },
  46890. enumerable: true,
  46891. configurable: true
  46892. });
  46893. Object.defineProperty(PointLight.prototype, "direction", {
  46894. /**
  46895. * Gets the direction if it has been set.
  46896. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46897. */
  46898. get: function () {
  46899. return this._direction;
  46900. },
  46901. /**
  46902. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46903. */
  46904. set: function (value) {
  46905. var previousNeedCube = this.needCube();
  46906. this._direction = value;
  46907. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46908. this._shadowGenerator.recreateShadowMap();
  46909. }
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. /**
  46915. * Returns the string "PointLight"
  46916. * @returns the class name
  46917. */
  46918. PointLight.prototype.getClassName = function () {
  46919. return "PointLight";
  46920. };
  46921. /**
  46922. * Returns the integer 0.
  46923. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46924. */
  46925. PointLight.prototype.getTypeID = function () {
  46926. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46927. };
  46928. /**
  46929. * Specifies wether or not the shadowmap should be a cube texture.
  46930. * @returns true if the shadowmap needs to be a cube texture.
  46931. */
  46932. PointLight.prototype.needCube = function () {
  46933. return !this.direction;
  46934. };
  46935. /**
  46936. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46937. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46938. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46939. */
  46940. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46941. if (this.direction) {
  46942. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46943. }
  46944. else {
  46945. switch (faceIndex) {
  46946. case 0:
  46947. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46948. case 1:
  46949. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46950. case 2:
  46951. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46952. case 3:
  46953. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46954. case 4:
  46955. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46956. case 5:
  46957. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46958. }
  46959. }
  46960. return BABYLON.Vector3.Zero();
  46961. };
  46962. /**
  46963. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46964. * - fov = PI / 2
  46965. * - aspect ratio : 1.0
  46966. * - z-near and far equal to the active camera minZ and maxZ.
  46967. * Returns the PointLight.
  46968. */
  46969. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46970. var activeCamera = this.getScene().activeCamera;
  46971. if (!activeCamera) {
  46972. return;
  46973. }
  46974. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46975. };
  46976. PointLight.prototype._buildUniformLayout = function () {
  46977. this._uniformBuffer.addUniform("vLightData", 4);
  46978. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46979. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46980. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46981. this._uniformBuffer.addUniform("depthValues", 2);
  46982. this._uniformBuffer.create();
  46983. };
  46984. /**
  46985. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46986. * @param effect The effect to update
  46987. * @param lightIndex The index of the light in the effect to update
  46988. * @returns The point light
  46989. */
  46990. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46991. if (this.computeTransformedInformation()) {
  46992. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46993. return this;
  46994. }
  46995. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46996. return this;
  46997. };
  46998. __decorate([
  46999. BABYLON.serialize()
  47000. ], PointLight.prototype, "shadowAngle", null);
  47001. return PointLight;
  47002. }(BABYLON.ShadowLight));
  47003. BABYLON.PointLight = PointLight;
  47004. })(BABYLON || (BABYLON = {}));
  47005. //# sourceMappingURL=babylon.pointLight.js.map
  47006. "use strict";
  47007. var BABYLON;
  47008. (function (BABYLON) {
  47009. /**
  47010. * A directional light is defined by a direction (what a surprise!).
  47011. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  47012. * 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.
  47013. * Documentation: https://doc.babylonjs.com/babylon101/lights
  47014. */
  47015. var DirectionalLight = /** @class */ (function (_super) {
  47016. __extends(DirectionalLight, _super);
  47017. /**
  47018. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  47019. * The directional light is emitted from everywhere in the given direction.
  47020. * It can cast shawdows.
  47021. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47022. * @param name The friendly name of the light
  47023. * @param direction The direction of the light
  47024. * @param scene The scene the light belongs to
  47025. */
  47026. function DirectionalLight(name, direction, scene) {
  47027. var _this = _super.call(this, name, scene) || this;
  47028. _this._shadowFrustumSize = 0;
  47029. _this._shadowOrthoScale = 0.1;
  47030. /**
  47031. * Automatically compute the projection matrix to best fit (including all the casters)
  47032. * on each frame.
  47033. */
  47034. _this.autoUpdateExtends = true;
  47035. // Cache
  47036. _this._orthoLeft = Number.MAX_VALUE;
  47037. _this._orthoRight = Number.MIN_VALUE;
  47038. _this._orthoTop = Number.MIN_VALUE;
  47039. _this._orthoBottom = Number.MAX_VALUE;
  47040. _this.position = direction.scale(-1.0);
  47041. _this.direction = direction;
  47042. return _this;
  47043. }
  47044. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  47045. /**
  47046. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  47047. */
  47048. get: function () {
  47049. return this._shadowFrustumSize;
  47050. },
  47051. /**
  47052. * Specifies a fix frustum size for the shadow generation.
  47053. */
  47054. set: function (value) {
  47055. this._shadowFrustumSize = value;
  47056. this.forceProjectionMatrixCompute();
  47057. },
  47058. enumerable: true,
  47059. configurable: true
  47060. });
  47061. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  47062. /**
  47063. * Gets the shadow projection scale against the optimal computed one.
  47064. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  47065. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  47066. */
  47067. get: function () {
  47068. return this._shadowOrthoScale;
  47069. },
  47070. /**
  47071. * Sets the shadow projection scale against the optimal computed one.
  47072. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  47073. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  47074. */
  47075. set: function (value) {
  47076. this._shadowOrthoScale = value;
  47077. this.forceProjectionMatrixCompute();
  47078. },
  47079. enumerable: true,
  47080. configurable: true
  47081. });
  47082. /**
  47083. * Returns the string "DirectionalLight".
  47084. * @return The class name
  47085. */
  47086. DirectionalLight.prototype.getClassName = function () {
  47087. return "DirectionalLight";
  47088. };
  47089. /**
  47090. * Returns the integer 1.
  47091. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47092. */
  47093. DirectionalLight.prototype.getTypeID = function () {
  47094. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  47095. };
  47096. /**
  47097. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  47098. * Returns the DirectionalLight Shadow projection matrix.
  47099. */
  47100. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47101. if (this.shadowFrustumSize > 0) {
  47102. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  47103. }
  47104. else {
  47105. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  47106. }
  47107. };
  47108. /**
  47109. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  47110. * Returns the DirectionalLight Shadow projection matrix.
  47111. */
  47112. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  47113. var activeCamera = this.getScene().activeCamera;
  47114. if (!activeCamera) {
  47115. return;
  47116. }
  47117. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  47118. };
  47119. /**
  47120. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  47121. * Returns the DirectionalLight Shadow projection matrix.
  47122. */
  47123. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47124. var activeCamera = this.getScene().activeCamera;
  47125. if (!activeCamera) {
  47126. return;
  47127. }
  47128. // Check extends
  47129. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  47130. var tempVector3 = BABYLON.Vector3.Zero();
  47131. this._orthoLeft = Number.MAX_VALUE;
  47132. this._orthoRight = Number.MIN_VALUE;
  47133. this._orthoTop = Number.MIN_VALUE;
  47134. this._orthoBottom = Number.MAX_VALUE;
  47135. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  47136. var mesh = renderList[meshIndex];
  47137. if (!mesh) {
  47138. continue;
  47139. }
  47140. var boundingInfo = mesh.getBoundingInfo();
  47141. var boundingBox = boundingInfo.boundingBox;
  47142. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  47143. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  47144. if (tempVector3.x < this._orthoLeft)
  47145. this._orthoLeft = tempVector3.x;
  47146. if (tempVector3.y < this._orthoBottom)
  47147. this._orthoBottom = tempVector3.y;
  47148. if (tempVector3.x > this._orthoRight)
  47149. this._orthoRight = tempVector3.x;
  47150. if (tempVector3.y > this._orthoTop)
  47151. this._orthoTop = tempVector3.y;
  47152. }
  47153. }
  47154. }
  47155. var xOffset = this._orthoRight - this._orthoLeft;
  47156. var yOffset = this._orthoTop - this._orthoBottom;
  47157. 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);
  47158. };
  47159. DirectionalLight.prototype._buildUniformLayout = function () {
  47160. this._uniformBuffer.addUniform("vLightData", 4);
  47161. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47162. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47163. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47164. this._uniformBuffer.addUniform("depthValues", 2);
  47165. this._uniformBuffer.create();
  47166. };
  47167. /**
  47168. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  47169. * @param effect The effect to update
  47170. * @param lightIndex The index of the light in the effect to update
  47171. * @returns The directional light
  47172. */
  47173. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  47174. if (this.computeTransformedInformation()) {
  47175. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  47176. return this;
  47177. }
  47178. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  47179. return this;
  47180. };
  47181. /**
  47182. * Gets the minZ used for shadow according to both the scene and the light.
  47183. *
  47184. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  47185. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  47186. * @param activeCamera The camera we are returning the min for
  47187. * @returns the depth min z
  47188. */
  47189. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  47190. return 1;
  47191. };
  47192. /**
  47193. * Gets the maxZ used for shadow according to both the scene and the light.
  47194. *
  47195. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  47196. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  47197. * @param activeCamera The camera we are returning the max for
  47198. * @returns the depth max z
  47199. */
  47200. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  47201. return 1;
  47202. };
  47203. __decorate([
  47204. BABYLON.serialize()
  47205. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  47206. __decorate([
  47207. BABYLON.serialize()
  47208. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  47209. __decorate([
  47210. BABYLON.serialize()
  47211. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  47212. return DirectionalLight;
  47213. }(BABYLON.ShadowLight));
  47214. BABYLON.DirectionalLight = DirectionalLight;
  47215. })(BABYLON || (BABYLON = {}));
  47216. //# sourceMappingURL=babylon.directionalLight.js.map
  47217. "use strict";
  47218. var BABYLON;
  47219. (function (BABYLON) {
  47220. /**
  47221. * A spot light is defined by a position, a direction, an angle, and an exponent.
  47222. * These values define a cone of light starting from the position, emitting toward the direction.
  47223. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  47224. * and the exponent defines the speed of the decay of the light with distance (reach).
  47225. * Documentation: https://doc.babylonjs.com/babylon101/lights
  47226. */
  47227. var SpotLight = /** @class */ (function (_super) {
  47228. __extends(SpotLight, _super);
  47229. /**
  47230. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  47231. * It can cast shadows.
  47232. * Documentation : http://doc.babylonjs.com/tutorials/lights
  47233. * @param name The light friendly name
  47234. * @param position The position of the spot light in the scene
  47235. * @param direction The direction of the light in the scene
  47236. * @param angle The cone angle of the light in Radians
  47237. * @param exponent The light decay speed with the distance from the emission spot
  47238. * @param scene The scene the lights belongs to
  47239. */
  47240. function SpotLight(name, position, direction, angle, exponent, scene) {
  47241. var _this = _super.call(this, name, scene) || this;
  47242. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  47243. _this._projectionTextureLightNear = 1e-6;
  47244. _this._projectionTextureLightFar = 1000.0;
  47245. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  47246. _this._projectionTextureViewLightDirty = true;
  47247. _this._projectionTextureProjectionLightDirty = true;
  47248. _this._projectionTextureDirty = true;
  47249. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  47250. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  47251. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  47252. _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);
  47253. _this.position = position;
  47254. _this.direction = direction;
  47255. _this.angle = angle;
  47256. _this.exponent = exponent;
  47257. return _this;
  47258. }
  47259. Object.defineProperty(SpotLight.prototype, "angle", {
  47260. /**
  47261. * Gets the cone angle of the spot light in Radians.
  47262. */
  47263. get: function () {
  47264. return this._angle;
  47265. },
  47266. /**
  47267. * Sets the cone angle of the spot light in Radians.
  47268. */
  47269. set: function (value) {
  47270. this._angle = value;
  47271. this._projectionTextureProjectionLightDirty = true;
  47272. this.forceProjectionMatrixCompute();
  47273. },
  47274. enumerable: true,
  47275. configurable: true
  47276. });
  47277. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  47278. /**
  47279. * Allows scaling the angle of the light for shadow generation only.
  47280. */
  47281. get: function () {
  47282. return this._shadowAngleScale;
  47283. },
  47284. /**
  47285. * Allows scaling the angle of the light for shadow generation only.
  47286. */
  47287. set: function (value) {
  47288. this._shadowAngleScale = value;
  47289. this.forceProjectionMatrixCompute();
  47290. },
  47291. enumerable: true,
  47292. configurable: true
  47293. });
  47294. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  47295. /**
  47296. * Allows reading the projecton texture
  47297. */
  47298. get: function () {
  47299. return this._projectionTextureMatrix;
  47300. },
  47301. enumerable: true,
  47302. configurable: true
  47303. });
  47304. ;
  47305. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  47306. /**
  47307. * Gets the near clip of the Spotlight for texture projection.
  47308. */
  47309. get: function () {
  47310. return this._projectionTextureLightNear;
  47311. },
  47312. /**
  47313. * Sets the near clip of the Spotlight for texture projection.
  47314. */
  47315. set: function (value) {
  47316. this._projectionTextureLightNear = value;
  47317. this._projectionTextureProjectionLightDirty = true;
  47318. },
  47319. enumerable: true,
  47320. configurable: true
  47321. });
  47322. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  47323. /**
  47324. * Gets the far clip of the Spotlight for texture projection.
  47325. */
  47326. get: function () {
  47327. return this._projectionTextureLightFar;
  47328. },
  47329. /**
  47330. * Sets the far clip of the Spotlight for texture projection.
  47331. */
  47332. set: function (value) {
  47333. this._projectionTextureLightFar = value;
  47334. this._projectionTextureProjectionLightDirty = true;
  47335. },
  47336. enumerable: true,
  47337. configurable: true
  47338. });
  47339. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  47340. /**
  47341. * Gets the Up vector of the Spotlight for texture projection.
  47342. */
  47343. get: function () {
  47344. return this._projectionTextureUpDirection;
  47345. },
  47346. /**
  47347. * Sets the Up vector of the Spotlight for texture projection.
  47348. */
  47349. set: function (value) {
  47350. this._projectionTextureUpDirection = value;
  47351. this._projectionTextureProjectionLightDirty = true;
  47352. },
  47353. enumerable: true,
  47354. configurable: true
  47355. });
  47356. ;
  47357. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  47358. /**
  47359. * Gets the projection texture of the light.
  47360. */
  47361. get: function () {
  47362. return this._projectionTexture;
  47363. },
  47364. /**
  47365. * Sets the projection texture of the light.
  47366. */
  47367. set: function (value) {
  47368. this._projectionTexture = value;
  47369. this._projectionTextureDirty = true;
  47370. },
  47371. enumerable: true,
  47372. configurable: true
  47373. });
  47374. /**
  47375. * Returns the string "SpotLight".
  47376. * @returns the class name
  47377. */
  47378. SpotLight.prototype.getClassName = function () {
  47379. return "SpotLight";
  47380. };
  47381. /**
  47382. * Returns the integer 2.
  47383. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  47384. */
  47385. SpotLight.prototype.getTypeID = function () {
  47386. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  47387. };
  47388. /**
  47389. * Overrides the direction setter to recompute the projection texture view light Matrix.
  47390. */
  47391. SpotLight.prototype._setDirection = function (value) {
  47392. _super.prototype._setDirection.call(this, value);
  47393. this._projectionTextureViewLightDirty = true;
  47394. };
  47395. /**
  47396. * Overrides the position setter to recompute the projection texture view light Matrix.
  47397. */
  47398. SpotLight.prototype._setPosition = function (value) {
  47399. _super.prototype._setPosition.call(this, value);
  47400. this._projectionTextureViewLightDirty = true;
  47401. };
  47402. /**
  47403. * 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.
  47404. * Returns the SpotLight.
  47405. */
  47406. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  47407. var activeCamera = this.getScene().activeCamera;
  47408. if (!activeCamera) {
  47409. return;
  47410. }
  47411. this._shadowAngleScale = this._shadowAngleScale || 1;
  47412. var angle = this._shadowAngleScale * this._angle;
  47413. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  47414. };
  47415. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  47416. this._projectionTextureViewLightDirty = false;
  47417. this._projectionTextureDirty = true;
  47418. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  47419. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  47420. };
  47421. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  47422. this._projectionTextureProjectionLightDirty = false;
  47423. this._projectionTextureDirty = true;
  47424. var light_far = this.projectionTextureLightFar;
  47425. var light_near = this.projectionTextureLightNear;
  47426. var P = light_far / (light_far - light_near);
  47427. var Q = -P * light_near;
  47428. var S = 1.0 / Math.tan(this._angle / 2.0);
  47429. var A = 1.0;
  47430. 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);
  47431. };
  47432. /**
  47433. * Main function for light texture projection matrix computing.
  47434. */
  47435. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  47436. this._projectionTextureDirty = false;
  47437. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  47438. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  47439. };
  47440. SpotLight.prototype._buildUniformLayout = function () {
  47441. this._uniformBuffer.addUniform("vLightData", 4);
  47442. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  47443. this._uniformBuffer.addUniform("vLightSpecular", 3);
  47444. this._uniformBuffer.addUniform("vLightDirection", 3);
  47445. this._uniformBuffer.addUniform("shadowsInfo", 3);
  47446. this._uniformBuffer.addUniform("depthValues", 2);
  47447. this._uniformBuffer.create();
  47448. };
  47449. /**
  47450. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  47451. * @param effect The effect to update
  47452. * @param lightIndex The index of the light in the effect to update
  47453. * @returns The spot light
  47454. */
  47455. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  47456. var normalizeDirection;
  47457. if (this.computeTransformedInformation()) {
  47458. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  47459. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  47460. }
  47461. else {
  47462. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  47463. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  47464. }
  47465. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  47466. if (this.projectionTexture && this.projectionTexture.isReady()) {
  47467. if (this._projectionTextureViewLightDirty) {
  47468. this._computeProjectionTextureViewLightMatrix();
  47469. }
  47470. if (this._projectionTextureProjectionLightDirty) {
  47471. this._computeProjectionTextureProjectionLightMatrix();
  47472. }
  47473. if (this._projectionTextureDirty) {
  47474. this._computeProjectionTextureMatrix();
  47475. }
  47476. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  47477. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  47478. }
  47479. return this;
  47480. };
  47481. /**
  47482. * Disposes the light and the associated resources.
  47483. */
  47484. SpotLight.prototype.dispose = function () {
  47485. _super.prototype.dispose.call(this);
  47486. if (this._projectionTexture) {
  47487. this._projectionTexture.dispose();
  47488. }
  47489. };
  47490. __decorate([
  47491. BABYLON.serialize()
  47492. ], SpotLight.prototype, "angle", null);
  47493. __decorate([
  47494. BABYLON.serialize()
  47495. ], SpotLight.prototype, "shadowAngleScale", null);
  47496. __decorate([
  47497. BABYLON.serialize()
  47498. ], SpotLight.prototype, "exponent", void 0);
  47499. __decorate([
  47500. BABYLON.serialize()
  47501. ], SpotLight.prototype, "projectionTextureLightNear", null);
  47502. __decorate([
  47503. BABYLON.serialize()
  47504. ], SpotLight.prototype, "projectionTextureLightFar", null);
  47505. __decorate([
  47506. BABYLON.serialize()
  47507. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  47508. __decorate([
  47509. BABYLON.serializeAsTexture("projectedLightTexture")
  47510. ], SpotLight.prototype, "_projectionTexture", void 0);
  47511. return SpotLight;
  47512. }(BABYLON.ShadowLight));
  47513. BABYLON.SpotLight = SpotLight;
  47514. })(BABYLON || (BABYLON = {}));
  47515. //# sourceMappingURL=babylon.spotLight.js.map
  47516. "use strict";
  47517. var BABYLON;
  47518. (function (BABYLON) {
  47519. /**
  47520. * Class used to override all child animations of a given target
  47521. */
  47522. var AnimationPropertiesOverride = /** @class */ (function () {
  47523. function AnimationPropertiesOverride() {
  47524. /**
  47525. * Gets or sets a value indicating if animation blending must be used
  47526. */
  47527. this.enableBlending = false;
  47528. /**
  47529. * Gets or sets the blending speed to use when enableBlending is true
  47530. */
  47531. this.blendingSpeed = 0.01;
  47532. /**
  47533. * Gets or sets the default loop mode to use
  47534. */
  47535. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  47536. }
  47537. return AnimationPropertiesOverride;
  47538. }());
  47539. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  47540. })(BABYLON || (BABYLON = {}));
  47541. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  47542. "use strict";
  47543. var BABYLON;
  47544. (function (BABYLON) {
  47545. var AnimationRange = /** @class */ (function () {
  47546. function AnimationRange(name, from, to) {
  47547. this.name = name;
  47548. this.from = from;
  47549. this.to = to;
  47550. }
  47551. AnimationRange.prototype.clone = function () {
  47552. return new AnimationRange(this.name, this.from, this.to);
  47553. };
  47554. return AnimationRange;
  47555. }());
  47556. BABYLON.AnimationRange = AnimationRange;
  47557. /**
  47558. * Composed of a frame, and an action function
  47559. */
  47560. var AnimationEvent = /** @class */ (function () {
  47561. function AnimationEvent(frame, action, onlyOnce) {
  47562. this.frame = frame;
  47563. this.action = action;
  47564. this.onlyOnce = onlyOnce;
  47565. this.isDone = false;
  47566. }
  47567. return AnimationEvent;
  47568. }());
  47569. BABYLON.AnimationEvent = AnimationEvent;
  47570. var PathCursor = /** @class */ (function () {
  47571. function PathCursor(path) {
  47572. this.path = path;
  47573. this._onchange = new Array();
  47574. this.value = 0;
  47575. this.animations = new Array();
  47576. }
  47577. PathCursor.prototype.getPoint = function () {
  47578. var point = this.path.getPointAtLengthPosition(this.value);
  47579. return new BABYLON.Vector3(point.x, 0, point.y);
  47580. };
  47581. PathCursor.prototype.moveAhead = function (step) {
  47582. if (step === void 0) { step = 0.002; }
  47583. this.move(step);
  47584. return this;
  47585. };
  47586. PathCursor.prototype.moveBack = function (step) {
  47587. if (step === void 0) { step = 0.002; }
  47588. this.move(-step);
  47589. return this;
  47590. };
  47591. PathCursor.prototype.move = function (step) {
  47592. if (Math.abs(step) > 1) {
  47593. throw "step size should be less than 1.";
  47594. }
  47595. this.value += step;
  47596. this.ensureLimits();
  47597. this.raiseOnChange();
  47598. return this;
  47599. };
  47600. PathCursor.prototype.ensureLimits = function () {
  47601. while (this.value > 1) {
  47602. this.value -= 1;
  47603. }
  47604. while (this.value < 0) {
  47605. this.value += 1;
  47606. }
  47607. return this;
  47608. };
  47609. // used by animation engine
  47610. PathCursor.prototype.raiseOnChange = function () {
  47611. var _this = this;
  47612. this._onchange.forEach(function (f) { return f(_this); });
  47613. return this;
  47614. };
  47615. PathCursor.prototype.onchange = function (f) {
  47616. this._onchange.push(f);
  47617. return this;
  47618. };
  47619. return PathCursor;
  47620. }());
  47621. BABYLON.PathCursor = PathCursor;
  47622. var AnimationKeyInterpolation;
  47623. (function (AnimationKeyInterpolation) {
  47624. /**
  47625. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  47626. */
  47627. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  47628. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  47629. var Animation = /** @class */ (function () {
  47630. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  47631. this.name = name;
  47632. this.targetProperty = targetProperty;
  47633. this.framePerSecond = framePerSecond;
  47634. this.dataType = dataType;
  47635. this.loopMode = loopMode;
  47636. this.enableBlending = enableBlending;
  47637. this._runtimeAnimations = new Array();
  47638. // The set of event that will be linked to this animation
  47639. this._events = new Array();
  47640. this.blendingSpeed = 0.01;
  47641. this._ranges = {};
  47642. this.targetPropertyPath = targetProperty.split(".");
  47643. this.dataType = dataType;
  47644. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  47645. }
  47646. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  47647. var dataType = undefined;
  47648. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  47649. dataType = Animation.ANIMATIONTYPE_FLOAT;
  47650. }
  47651. else if (from instanceof BABYLON.Quaternion) {
  47652. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  47653. }
  47654. else if (from instanceof BABYLON.Vector3) {
  47655. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  47656. }
  47657. else if (from instanceof BABYLON.Vector2) {
  47658. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  47659. }
  47660. else if (from instanceof BABYLON.Color3) {
  47661. dataType = Animation.ANIMATIONTYPE_COLOR3;
  47662. }
  47663. else if (from instanceof BABYLON.Size) {
  47664. dataType = Animation.ANIMATIONTYPE_SIZE;
  47665. }
  47666. if (dataType == undefined) {
  47667. return null;
  47668. }
  47669. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  47670. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  47671. animation.setKeys(keys);
  47672. if (easingFunction !== undefined) {
  47673. animation.setEasingFunction(easingFunction);
  47674. }
  47675. return animation;
  47676. };
  47677. /**
  47678. * Sets up an animation.
  47679. * @param property the property to animate
  47680. * @param animationType the animation type to apply
  47681. * @param easingFunction the easing function used in the animation
  47682. * @returns The created animation
  47683. */
  47684. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  47685. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  47686. animation.setEasingFunction(easingFunction);
  47687. return animation;
  47688. };
  47689. /**
  47690. * Create and start an animation on a node
  47691. * @param {string} name defines the name of the global animation that will be run on all nodes
  47692. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47693. * @param {string} targetProperty defines property to animate
  47694. * @param {number} framePerSecond defines the number of frame per second yo use
  47695. * @param {number} totalFrame defines the number of frames in total
  47696. * @param {any} from defines the initial value
  47697. * @param {any} to defines the final value
  47698. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47699. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47700. * @param onAnimationEnd defines the callback to call when animation end
  47701. * @returns the animatable created for this animation
  47702. */
  47703. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47704. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47705. if (!animation) {
  47706. return null;
  47707. }
  47708. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47709. };
  47710. /**
  47711. * Create and start an animation on a node and its descendants
  47712. * @param {string} name defines the name of the global animation that will be run on all nodes
  47713. * @param {BABYLON.Node} node defines the root node where the animation will take place
  47714. * @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.
  47715. * @param {string} targetProperty defines property to animate
  47716. * @param {number} framePerSecond defines the number of frame per second yo use
  47717. * @param {number} totalFrame defines the number of frames in total
  47718. * @param {any} from defines the initial value
  47719. * @param {any} to defines the final value
  47720. * @param {number} loopMode defines which loop mode you want to use (off by default)
  47721. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  47722. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  47723. * @returns the list of animatables created for all nodes
  47724. * @example https://www.babylonjs-playground.com/#MH0VLI
  47725. */
  47726. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47727. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47728. if (!animation) {
  47729. return null;
  47730. }
  47731. var scene = node.getScene();
  47732. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47733. };
  47734. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  47735. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  47736. if (!animation) {
  47737. return null;
  47738. }
  47739. node.animations.push(animation);
  47740. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  47741. };
  47742. /**
  47743. * Transition property of the Camera to the target Value.
  47744. * @param property The property to transition
  47745. * @param targetValue The target Value of the property
  47746. * @param host The object where the property to animate belongs
  47747. * @param scene Scene used to run the animation
  47748. * @param frameRate Framerate (in frame/s) to use
  47749. * @param transition The transition type we want to use
  47750. * @param duration The duration of the animation, in milliseconds
  47751. * @param onAnimationEnd Call back trigger at the end of the animation.
  47752. */
  47753. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  47754. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  47755. if (duration <= 0) {
  47756. host[property] = targetValue;
  47757. if (onAnimationEnd) {
  47758. onAnimationEnd();
  47759. }
  47760. return null;
  47761. }
  47762. var endFrame = frameRate * (duration / 1000);
  47763. transition.setKeys([{
  47764. frame: 0,
  47765. value: host[property].clone ? host[property].clone() : host[property]
  47766. },
  47767. {
  47768. frame: endFrame,
  47769. value: targetValue
  47770. }]);
  47771. if (!host.animations) {
  47772. host.animations = [];
  47773. }
  47774. host.animations.push(transition);
  47775. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47776. animation.onAnimationEnd = onAnimationEnd;
  47777. return animation;
  47778. };
  47779. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47780. /**
  47781. * Return the array of runtime animations currently using this animation
  47782. */
  47783. get: function () {
  47784. return this._runtimeAnimations;
  47785. },
  47786. enumerable: true,
  47787. configurable: true
  47788. });
  47789. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47790. get: function () {
  47791. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47792. var runtimeAnimation = _a[_i];
  47793. if (!runtimeAnimation.isStopped) {
  47794. return true;
  47795. }
  47796. }
  47797. return false;
  47798. },
  47799. enumerable: true,
  47800. configurable: true
  47801. });
  47802. // Methods
  47803. /**
  47804. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47805. */
  47806. Animation.prototype.toString = function (fullDetails) {
  47807. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47808. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47809. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47810. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47811. if (fullDetails) {
  47812. ret += ", Ranges: {";
  47813. var first = true;
  47814. for (var name in this._ranges) {
  47815. if (first) {
  47816. ret += ", ";
  47817. first = false;
  47818. }
  47819. ret += name;
  47820. }
  47821. ret += "}";
  47822. }
  47823. return ret;
  47824. };
  47825. /**
  47826. * Add an event to this animation.
  47827. */
  47828. Animation.prototype.addEvent = function (event) {
  47829. this._events.push(event);
  47830. };
  47831. /**
  47832. * Remove all events found at the given frame
  47833. * @param frame
  47834. */
  47835. Animation.prototype.removeEvents = function (frame) {
  47836. for (var index = 0; index < this._events.length; index++) {
  47837. if (this._events[index].frame === frame) {
  47838. this._events.splice(index, 1);
  47839. index--;
  47840. }
  47841. }
  47842. };
  47843. Animation.prototype.getEvents = function () {
  47844. return this._events;
  47845. };
  47846. Animation.prototype.createRange = function (name, from, to) {
  47847. // check name not already in use; could happen for bones after serialized
  47848. if (!this._ranges[name]) {
  47849. this._ranges[name] = new AnimationRange(name, from, to);
  47850. }
  47851. };
  47852. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47853. if (deleteFrames === void 0) { deleteFrames = true; }
  47854. var range = this._ranges[name];
  47855. if (!range) {
  47856. return;
  47857. }
  47858. if (deleteFrames) {
  47859. var from = range.from;
  47860. var to = range.to;
  47861. // this loop MUST go high to low for multiple splices to work
  47862. for (var key = this._keys.length - 1; key >= 0; key--) {
  47863. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47864. this._keys.splice(key, 1);
  47865. }
  47866. }
  47867. }
  47868. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47869. };
  47870. Animation.prototype.getRange = function (name) {
  47871. return this._ranges[name];
  47872. };
  47873. Animation.prototype.getKeys = function () {
  47874. return this._keys;
  47875. };
  47876. Animation.prototype.getHighestFrame = function () {
  47877. var ret = 0;
  47878. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47879. if (ret < this._keys[key].frame) {
  47880. ret = this._keys[key].frame;
  47881. }
  47882. }
  47883. return ret;
  47884. };
  47885. Animation.prototype.getEasingFunction = function () {
  47886. return this._easingFunction;
  47887. };
  47888. Animation.prototype.setEasingFunction = function (easingFunction) {
  47889. this._easingFunction = easingFunction;
  47890. };
  47891. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47892. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47893. };
  47894. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47895. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47896. };
  47897. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47898. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47899. };
  47900. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47901. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47902. };
  47903. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47904. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47905. };
  47906. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47907. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47908. };
  47909. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47910. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47911. };
  47912. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47913. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47914. };
  47915. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47916. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47917. };
  47918. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47919. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47920. };
  47921. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47922. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47923. };
  47924. Animation.prototype.clone = function () {
  47925. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47926. clone.enableBlending = this.enableBlending;
  47927. clone.blendingSpeed = this.blendingSpeed;
  47928. if (this._keys) {
  47929. clone.setKeys(this._keys);
  47930. }
  47931. if (this._ranges) {
  47932. clone._ranges = {};
  47933. for (var name in this._ranges) {
  47934. var range = this._ranges[name];
  47935. if (!range) {
  47936. continue;
  47937. }
  47938. clone._ranges[name] = range.clone();
  47939. }
  47940. }
  47941. return clone;
  47942. };
  47943. Animation.prototype.setKeys = function (values) {
  47944. this._keys = values.slice(0);
  47945. };
  47946. Animation.prototype.serialize = function () {
  47947. var serializationObject = {};
  47948. serializationObject.name = this.name;
  47949. serializationObject.property = this.targetProperty;
  47950. serializationObject.framePerSecond = this.framePerSecond;
  47951. serializationObject.dataType = this.dataType;
  47952. serializationObject.loopBehavior = this.loopMode;
  47953. serializationObject.enableBlending = this.enableBlending;
  47954. serializationObject.blendingSpeed = this.blendingSpeed;
  47955. var dataType = this.dataType;
  47956. serializationObject.keys = [];
  47957. var keys = this.getKeys();
  47958. for (var index = 0; index < keys.length; index++) {
  47959. var animationKey = keys[index];
  47960. var key = {};
  47961. key.frame = animationKey.frame;
  47962. switch (dataType) {
  47963. case Animation.ANIMATIONTYPE_FLOAT:
  47964. key.values = [animationKey.value];
  47965. break;
  47966. case Animation.ANIMATIONTYPE_QUATERNION:
  47967. case Animation.ANIMATIONTYPE_MATRIX:
  47968. case Animation.ANIMATIONTYPE_VECTOR3:
  47969. case Animation.ANIMATIONTYPE_COLOR3:
  47970. key.values = animationKey.value.asArray();
  47971. break;
  47972. }
  47973. serializationObject.keys.push(key);
  47974. }
  47975. serializationObject.ranges = [];
  47976. for (var name in this._ranges) {
  47977. var source = this._ranges[name];
  47978. if (!source) {
  47979. continue;
  47980. }
  47981. var range = {};
  47982. range.name = name;
  47983. range.from = source.from;
  47984. range.to = source.to;
  47985. serializationObject.ranges.push(range);
  47986. }
  47987. return serializationObject;
  47988. };
  47989. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47990. get: function () {
  47991. return Animation._ANIMATIONTYPE_FLOAT;
  47992. },
  47993. enumerable: true,
  47994. configurable: true
  47995. });
  47996. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47997. get: function () {
  47998. return Animation._ANIMATIONTYPE_VECTOR3;
  47999. },
  48000. enumerable: true,
  48001. configurable: true
  48002. });
  48003. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  48004. get: function () {
  48005. return Animation._ANIMATIONTYPE_VECTOR2;
  48006. },
  48007. enumerable: true,
  48008. configurable: true
  48009. });
  48010. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  48011. get: function () {
  48012. return Animation._ANIMATIONTYPE_SIZE;
  48013. },
  48014. enumerable: true,
  48015. configurable: true
  48016. });
  48017. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  48018. get: function () {
  48019. return Animation._ANIMATIONTYPE_QUATERNION;
  48020. },
  48021. enumerable: true,
  48022. configurable: true
  48023. });
  48024. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  48025. get: function () {
  48026. return Animation._ANIMATIONTYPE_MATRIX;
  48027. },
  48028. enumerable: true,
  48029. configurable: true
  48030. });
  48031. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  48032. get: function () {
  48033. return Animation._ANIMATIONTYPE_COLOR3;
  48034. },
  48035. enumerable: true,
  48036. configurable: true
  48037. });
  48038. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  48039. get: function () {
  48040. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  48041. },
  48042. enumerable: true,
  48043. configurable: true
  48044. });
  48045. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  48046. get: function () {
  48047. return Animation._ANIMATIONLOOPMODE_CYCLE;
  48048. },
  48049. enumerable: true,
  48050. configurable: true
  48051. });
  48052. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  48053. get: function () {
  48054. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  48055. },
  48056. enumerable: true,
  48057. configurable: true
  48058. });
  48059. Animation.Parse = function (parsedAnimation) {
  48060. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  48061. var dataType = parsedAnimation.dataType;
  48062. var keys = [];
  48063. var data;
  48064. var index;
  48065. if (parsedAnimation.enableBlending) {
  48066. animation.enableBlending = parsedAnimation.enableBlending;
  48067. }
  48068. if (parsedAnimation.blendingSpeed) {
  48069. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  48070. }
  48071. for (index = 0; index < parsedAnimation.keys.length; index++) {
  48072. var key = parsedAnimation.keys[index];
  48073. var inTangent;
  48074. var outTangent;
  48075. switch (dataType) {
  48076. case Animation.ANIMATIONTYPE_FLOAT:
  48077. data = key.values[0];
  48078. if (key.values.length >= 1) {
  48079. inTangent = key.values[1];
  48080. }
  48081. if (key.values.length >= 2) {
  48082. outTangent = key.values[2];
  48083. }
  48084. break;
  48085. case Animation.ANIMATIONTYPE_QUATERNION:
  48086. data = BABYLON.Quaternion.FromArray(key.values);
  48087. if (key.values.length >= 8) {
  48088. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  48089. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  48090. inTangent = _inTangent;
  48091. }
  48092. }
  48093. if (key.values.length >= 12) {
  48094. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  48095. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  48096. outTangent = _outTangent;
  48097. }
  48098. }
  48099. break;
  48100. case Animation.ANIMATIONTYPE_MATRIX:
  48101. data = BABYLON.Matrix.FromArray(key.values);
  48102. break;
  48103. case Animation.ANIMATIONTYPE_COLOR3:
  48104. data = BABYLON.Color3.FromArray(key.values);
  48105. break;
  48106. case Animation.ANIMATIONTYPE_VECTOR3:
  48107. default:
  48108. data = BABYLON.Vector3.FromArray(key.values);
  48109. break;
  48110. }
  48111. var keyData = {};
  48112. keyData.frame = key.frame;
  48113. keyData.value = data;
  48114. if (inTangent != undefined) {
  48115. keyData.inTangent = inTangent;
  48116. }
  48117. if (outTangent != undefined) {
  48118. keyData.outTangent = outTangent;
  48119. }
  48120. keys.push(keyData);
  48121. }
  48122. animation.setKeys(keys);
  48123. if (parsedAnimation.ranges) {
  48124. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  48125. data = parsedAnimation.ranges[index];
  48126. animation.createRange(data.name, data.from, data.to);
  48127. }
  48128. }
  48129. return animation;
  48130. };
  48131. Animation.AppendSerializedAnimations = function (source, destination) {
  48132. if (source.animations) {
  48133. destination.animations = [];
  48134. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  48135. var animation = source.animations[animationIndex];
  48136. destination.animations.push(animation.serialize());
  48137. }
  48138. }
  48139. };
  48140. Animation.AllowMatricesInterpolation = false;
  48141. // Statics
  48142. Animation._ANIMATIONTYPE_FLOAT = 0;
  48143. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  48144. Animation._ANIMATIONTYPE_QUATERNION = 2;
  48145. Animation._ANIMATIONTYPE_MATRIX = 3;
  48146. Animation._ANIMATIONTYPE_COLOR3 = 4;
  48147. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  48148. Animation._ANIMATIONTYPE_SIZE = 6;
  48149. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  48150. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  48151. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  48152. return Animation;
  48153. }());
  48154. BABYLON.Animation = Animation;
  48155. })(BABYLON || (BABYLON = {}));
  48156. //# sourceMappingURL=babylon.animation.js.map
  48157. "use strict";
  48158. var BABYLON;
  48159. (function (BABYLON) {
  48160. /**
  48161. * This class defines the direct association between an animation and a target
  48162. */
  48163. var TargetedAnimation = /** @class */ (function () {
  48164. function TargetedAnimation() {
  48165. }
  48166. return TargetedAnimation;
  48167. }());
  48168. BABYLON.TargetedAnimation = TargetedAnimation;
  48169. /**
  48170. * Use this class to create coordinated animations on multiple targets
  48171. */
  48172. var AnimationGroup = /** @class */ (function () {
  48173. function AnimationGroup(name, scene) {
  48174. if (scene === void 0) { scene = null; }
  48175. this.name = name;
  48176. this._targetedAnimations = new Array();
  48177. this._animatables = new Array();
  48178. this._from = Number.MAX_VALUE;
  48179. this._to = -Number.MAX_VALUE;
  48180. this._speedRatio = 1;
  48181. this.onAnimationEndObservable = new BABYLON.Observable();
  48182. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48183. this._scene.animationGroups.push(this);
  48184. }
  48185. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  48186. /**
  48187. * Define if the animations are started
  48188. */
  48189. get: function () {
  48190. return this._isStarted;
  48191. },
  48192. enumerable: true,
  48193. configurable: true
  48194. });
  48195. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  48196. /**
  48197. * Gets or sets the speed ratio to use for all animations
  48198. */
  48199. get: function () {
  48200. return this._speedRatio;
  48201. },
  48202. /**
  48203. * Gets or sets the speed ratio to use for all animations
  48204. */
  48205. set: function (value) {
  48206. if (this._speedRatio === value) {
  48207. return;
  48208. }
  48209. this._speedRatio = value;
  48210. for (var index = 0; index < this._animatables.length; index++) {
  48211. var animatable = this._animatables[index];
  48212. animatable.speedRatio = this._speedRatio;
  48213. }
  48214. },
  48215. enumerable: true,
  48216. configurable: true
  48217. });
  48218. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  48219. /**
  48220. * Gets the targeted animations for this animation group
  48221. */
  48222. get: function () {
  48223. return this._targetedAnimations;
  48224. },
  48225. enumerable: true,
  48226. configurable: true
  48227. });
  48228. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  48229. /**
  48230. * returning the list of animatables controlled by this animation group.
  48231. */
  48232. get: function () {
  48233. return this._animatables;
  48234. },
  48235. enumerable: true,
  48236. configurable: true
  48237. });
  48238. /**
  48239. * Add an animation (with its target) in the group
  48240. * @param animation defines the animation we want to add
  48241. * @param target defines the target of the animation
  48242. * @returns the {BABYLON.TargetedAnimation} object
  48243. */
  48244. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  48245. var targetedAnimation = {
  48246. animation: animation,
  48247. target: target
  48248. };
  48249. var keys = animation.getKeys();
  48250. if (this._from > keys[0].frame) {
  48251. this._from = keys[0].frame;
  48252. }
  48253. if (this._to < keys[keys.length - 1].frame) {
  48254. this._to = keys[keys.length - 1].frame;
  48255. }
  48256. this._targetedAnimations.push(targetedAnimation);
  48257. return targetedAnimation;
  48258. };
  48259. /**
  48260. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  48261. * It can add constant keys at begin or end
  48262. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  48263. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  48264. */
  48265. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  48266. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  48267. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  48268. beginFrame = Math.max(beginFrame, this._from);
  48269. endFrame = Math.min(endFrame, this._to);
  48270. for (var index = 0; index < this._targetedAnimations.length; index++) {
  48271. var targetedAnimation = this._targetedAnimations[index];
  48272. var keys = targetedAnimation.animation.getKeys();
  48273. var startKey = keys[0];
  48274. var endKey = keys[keys.length - 1];
  48275. if (startKey.frame > beginFrame) {
  48276. var newKey = {
  48277. frame: beginFrame,
  48278. value: startKey.value,
  48279. inTangent: startKey.inTangent,
  48280. outTangent: startKey.outTangent,
  48281. interpolation: startKey.interpolation
  48282. };
  48283. keys.splice(0, 0, newKey);
  48284. }
  48285. if (endKey.frame < endFrame) {
  48286. var newKey = {
  48287. frame: endFrame,
  48288. value: endKey.value,
  48289. inTangent: endKey.outTangent,
  48290. outTangent: endKey.outTangent,
  48291. interpolation: endKey.interpolation
  48292. };
  48293. keys.push(newKey);
  48294. }
  48295. }
  48296. return this;
  48297. };
  48298. /**
  48299. * Start all animations on given targets
  48300. * @param loop defines if animations must loop
  48301. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  48302. * @param from defines the from key (optional)
  48303. * @param to defines the to key (optional)
  48304. * @returns the current animation group
  48305. */
  48306. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  48307. var _this = this;
  48308. if (loop === void 0) { loop = false; }
  48309. if (speedRatio === void 0) { speedRatio = 1; }
  48310. if (this._isStarted || this._targetedAnimations.length === 0) {
  48311. return this;
  48312. }
  48313. var _loop_1 = function () {
  48314. var targetedAnimation = this_1._targetedAnimations[index];
  48315. if (!targetedAnimation.target.animations) {
  48316. targetedAnimation.target.animations = [];
  48317. }
  48318. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  48319. targetedAnimation.target.animations.push(targetedAnimation.animation);
  48320. }
  48321. 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 () {
  48322. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  48323. }));
  48324. };
  48325. var this_1 = this;
  48326. for (var index = 0; index < this._targetedAnimations.length; index++) {
  48327. _loop_1();
  48328. }
  48329. this._speedRatio = speedRatio;
  48330. this._isStarted = true;
  48331. return this;
  48332. };
  48333. /**
  48334. * Pause all animations
  48335. */
  48336. AnimationGroup.prototype.pause = function () {
  48337. if (!this._isStarted) {
  48338. return this;
  48339. }
  48340. for (var index = 0; index < this._animatables.length; index++) {
  48341. var animatable = this._animatables[index];
  48342. animatable.pause();
  48343. }
  48344. return this;
  48345. };
  48346. /**
  48347. * Play all animations to initial state
  48348. * This function will start() the animations if they were not started or will restart() them if they were paused
  48349. * @param loop defines if animations must loop
  48350. */
  48351. AnimationGroup.prototype.play = function (loop) {
  48352. if (this.isStarted) {
  48353. if (loop !== undefined) {
  48354. for (var index = 0; index < this._animatables.length; index++) {
  48355. var animatable = this._animatables[index];
  48356. animatable.loopAnimation = loop;
  48357. }
  48358. }
  48359. this.restart();
  48360. }
  48361. else {
  48362. this.start(loop, this._speedRatio);
  48363. }
  48364. return this;
  48365. };
  48366. /**
  48367. * Reset all animations to initial state
  48368. */
  48369. AnimationGroup.prototype.reset = function () {
  48370. if (!this._isStarted) {
  48371. return this;
  48372. }
  48373. for (var index = 0; index < this._animatables.length; index++) {
  48374. var animatable = this._animatables[index];
  48375. animatable.reset();
  48376. }
  48377. return this;
  48378. };
  48379. /**
  48380. * Restart animations from key 0
  48381. */
  48382. AnimationGroup.prototype.restart = function () {
  48383. if (!this._isStarted) {
  48384. return this;
  48385. }
  48386. for (var index = 0; index < this._animatables.length; index++) {
  48387. var animatable = this._animatables[index];
  48388. animatable.restart();
  48389. }
  48390. return this;
  48391. };
  48392. /**
  48393. * Stop all animations
  48394. */
  48395. AnimationGroup.prototype.stop = function () {
  48396. if (!this._isStarted) {
  48397. return this;
  48398. }
  48399. for (var index = 0; index < this._animatables.length; index++) {
  48400. var animatable = this._animatables[index];
  48401. animatable.stop();
  48402. }
  48403. this._isStarted = false;
  48404. return this;
  48405. };
  48406. /**
  48407. * Goes to a specific frame in this animation group
  48408. *
  48409. * @param frame the frame number to go to
  48410. * @return the animationGroup
  48411. */
  48412. AnimationGroup.prototype.goToFrame = function (frame) {
  48413. if (!this._isStarted) {
  48414. return this;
  48415. }
  48416. for (var index = 0; index < this._animatables.length; index++) {
  48417. var animatable = this._animatables[index];
  48418. animatable.goToFrame(frame);
  48419. }
  48420. return this;
  48421. };
  48422. /**
  48423. * Dispose all associated resources
  48424. */
  48425. AnimationGroup.prototype.dispose = function () {
  48426. this._targetedAnimations = [];
  48427. this._animatables = [];
  48428. var index = this._scene.animationGroups.indexOf(this);
  48429. if (index > -1) {
  48430. this._scene.animationGroups.splice(index, 1);
  48431. }
  48432. };
  48433. return AnimationGroup;
  48434. }());
  48435. BABYLON.AnimationGroup = AnimationGroup;
  48436. })(BABYLON || (BABYLON = {}));
  48437. //# sourceMappingURL=babylon.animationGroup.js.map
  48438. "use strict";
  48439. var BABYLON;
  48440. (function (BABYLON) {
  48441. var RuntimeAnimation = /** @class */ (function () {
  48442. /**
  48443. * Create a new RuntimeAnimation object
  48444. * @param target defines the target of the animation
  48445. * @param animation defines the source {BABYLON.Animation} object
  48446. * @param scene defines the hosting scene
  48447. * @param host defines the initiating Animatable
  48448. */
  48449. function RuntimeAnimation(target, animation, scene, host) {
  48450. this._currentFrame = 0;
  48451. this._offsetsCache = {};
  48452. this._highLimitsCache = {};
  48453. this._stopped = false;
  48454. this._blendingFactor = 0;
  48455. this._targetPath = "";
  48456. this._weight = 1.0;
  48457. this._ratioOffset = 0;
  48458. this._previousDelay = 0;
  48459. this._previousRatio = 0;
  48460. this._animation = animation;
  48461. this._target = target;
  48462. this._scene = scene;
  48463. this._host = host;
  48464. animation._runtimeAnimations.push(this);
  48465. }
  48466. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  48467. /**
  48468. * Gets the current frame
  48469. */
  48470. get: function () {
  48471. return this._currentFrame;
  48472. },
  48473. enumerable: true,
  48474. configurable: true
  48475. });
  48476. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  48477. /**
  48478. * Gets the weight of the runtime animation
  48479. */
  48480. get: function () {
  48481. return this._weight;
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  48487. /**
  48488. * Gets the original value of the runtime animation
  48489. */
  48490. get: function () {
  48491. return this._originalValue;
  48492. },
  48493. enumerable: true,
  48494. configurable: true
  48495. });
  48496. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  48497. /**
  48498. * Gets the current value of the runtime animation
  48499. */
  48500. get: function () {
  48501. return this._currentValue;
  48502. },
  48503. enumerable: true,
  48504. configurable: true
  48505. });
  48506. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  48507. /**
  48508. * Gets the path where to store the animated value in the target
  48509. */
  48510. get: function () {
  48511. return this._targetPath;
  48512. },
  48513. enumerable: true,
  48514. configurable: true
  48515. });
  48516. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  48517. /**
  48518. * Gets the actual target of the runtime animation
  48519. */
  48520. get: function () {
  48521. return this._activeTarget;
  48522. },
  48523. enumerable: true,
  48524. configurable: true
  48525. });
  48526. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  48527. get: function () {
  48528. return this._animation;
  48529. },
  48530. enumerable: true,
  48531. configurable: true
  48532. });
  48533. RuntimeAnimation.prototype.reset = function () {
  48534. this._offsetsCache = {};
  48535. this._highLimitsCache = {};
  48536. this._currentFrame = 0;
  48537. this._blendingFactor = 0;
  48538. this._originalValue = null;
  48539. };
  48540. RuntimeAnimation.prototype.isStopped = function () {
  48541. return this._stopped;
  48542. };
  48543. RuntimeAnimation.prototype.dispose = function () {
  48544. var index = this._animation.runtimeAnimations.indexOf(this);
  48545. if (index > -1) {
  48546. this._animation.runtimeAnimations.splice(index, 1);
  48547. }
  48548. };
  48549. RuntimeAnimation.prototype._getKeyValue = function (value) {
  48550. if (typeof value === "function") {
  48551. return value();
  48552. }
  48553. return value;
  48554. };
  48555. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  48556. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  48557. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  48558. }
  48559. this._currentFrame = currentFrame;
  48560. var keys = this._animation.getKeys();
  48561. // Try to get a hash to find the right key
  48562. 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));
  48563. if (keys[startKeyIndex].frame >= currentFrame) {
  48564. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  48565. startKeyIndex--;
  48566. }
  48567. }
  48568. for (var key = startKeyIndex; key < keys.length; key++) {
  48569. var endKey = keys[key + 1];
  48570. if (endKey.frame >= currentFrame) {
  48571. var startKey = keys[key];
  48572. var startValue = this._getKeyValue(startKey.value);
  48573. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  48574. return startValue;
  48575. }
  48576. var endValue = this._getKeyValue(endKey.value);
  48577. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  48578. var frameDelta = endKey.frame - startKey.frame;
  48579. // gradient : percent of currentFrame between the frame inf and the frame sup
  48580. var gradient = (currentFrame - startKey.frame) / frameDelta;
  48581. // check for easingFunction and correction of gradient
  48582. var easingFunction = this._animation.getEasingFunction();
  48583. if (easingFunction != null) {
  48584. gradient = easingFunction.ease(gradient);
  48585. }
  48586. switch (this._animation.dataType) {
  48587. // Float
  48588. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48589. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  48590. switch (loopMode) {
  48591. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48592. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48593. return floatValue;
  48594. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48595. return offsetValue * repeatCount + floatValue;
  48596. }
  48597. break;
  48598. // Quaternion
  48599. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48600. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  48601. switch (loopMode) {
  48602. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48603. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48604. return quatValue;
  48605. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48606. return quatValue.add(offsetValue.scale(repeatCount));
  48607. }
  48608. return quatValue;
  48609. // Vector3
  48610. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48611. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  48612. switch (loopMode) {
  48613. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48614. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48615. return vec3Value;
  48616. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48617. return vec3Value.add(offsetValue.scale(repeatCount));
  48618. }
  48619. // Vector2
  48620. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48621. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  48622. switch (loopMode) {
  48623. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48624. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48625. return vec2Value;
  48626. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48627. return vec2Value.add(offsetValue.scale(repeatCount));
  48628. }
  48629. // Size
  48630. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48631. switch (loopMode) {
  48632. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48633. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48634. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  48635. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48636. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  48637. }
  48638. // Color3
  48639. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48640. switch (loopMode) {
  48641. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48642. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48643. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  48644. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48645. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  48646. }
  48647. // Matrix
  48648. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  48649. switch (loopMode) {
  48650. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  48651. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  48652. if (BABYLON.Animation.AllowMatricesInterpolation) {
  48653. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  48654. }
  48655. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  48656. return startValue;
  48657. }
  48658. default:
  48659. break;
  48660. }
  48661. break;
  48662. }
  48663. }
  48664. return this._getKeyValue(keys[keys.length - 1].value);
  48665. };
  48666. /**
  48667. * Affect the interpolated value to the target
  48668. * @param currentValue defines the value computed by the animation
  48669. * @param weight defines the weight to apply to this value
  48670. */
  48671. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  48672. if (weight === void 0) { weight = 1.0; }
  48673. // Set value
  48674. var path;
  48675. var destination;
  48676. var targetPropertyPath = this._animation.targetPropertyPath;
  48677. if (targetPropertyPath.length > 1) {
  48678. var property = this._target[targetPropertyPath[0]];
  48679. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  48680. property = property[targetPropertyPath[index]];
  48681. }
  48682. path = targetPropertyPath[targetPropertyPath.length - 1];
  48683. destination = property;
  48684. }
  48685. else {
  48686. path = targetPropertyPath[0];
  48687. destination = this._target;
  48688. }
  48689. this._targetPath = path;
  48690. this._activeTarget = destination;
  48691. this._weight = weight;
  48692. // Blending
  48693. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  48694. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  48695. if (enableBlending && this._blendingFactor <= 1.0) {
  48696. if (!this._originalBlendValue) {
  48697. var originalValue = destination[path];
  48698. if (originalValue.clone) {
  48699. this._originalBlendValue = originalValue.clone();
  48700. }
  48701. else {
  48702. this._originalBlendValue = originalValue;
  48703. }
  48704. }
  48705. }
  48706. if (weight !== -1.0) {
  48707. if (!this._originalValue) {
  48708. var originalValue = void 0;
  48709. if (destination.getRestPose) {
  48710. originalValue = destination.getRestPose();
  48711. }
  48712. else {
  48713. originalValue = destination[path];
  48714. }
  48715. if (originalValue.clone) {
  48716. this._originalValue = originalValue.clone();
  48717. }
  48718. else {
  48719. this._originalValue = originalValue;
  48720. }
  48721. }
  48722. }
  48723. if (enableBlending && this._blendingFactor <= 1.0) {
  48724. if (this._originalBlendValue.prototype) {
  48725. if (this._originalBlendValue.prototype.Lerp) {
  48726. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  48727. }
  48728. else {
  48729. this._currentValue = currentValue;
  48730. }
  48731. }
  48732. else if (this._originalBlendValue.m) {
  48733. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  48734. }
  48735. else {
  48736. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  48737. }
  48738. this._blendingFactor += blendingSpeed;
  48739. }
  48740. else {
  48741. this._currentValue = currentValue;
  48742. }
  48743. if (weight !== -1.0) {
  48744. this._scene._registerTargetForLateAnimationBinding(this);
  48745. }
  48746. else {
  48747. destination[path] = this._currentValue;
  48748. }
  48749. if (this._target.markAsDirty) {
  48750. this._target.markAsDirty(this._animation.targetProperty);
  48751. }
  48752. };
  48753. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  48754. if (this._target && this._target.animationPropertiesOverride) {
  48755. return this._target.animationPropertiesOverride.loopMode;
  48756. }
  48757. return this._animation.loopMode;
  48758. };
  48759. /**
  48760. * Move the current animation to a given frame
  48761. * @param frame defines the frame to move to
  48762. */
  48763. RuntimeAnimation.prototype.goToFrame = function (frame) {
  48764. var keys = this._animation.getKeys();
  48765. if (frame < keys[0].frame) {
  48766. frame = keys[0].frame;
  48767. }
  48768. else if (frame > keys[keys.length - 1].frame) {
  48769. frame = keys[keys.length - 1].frame;
  48770. }
  48771. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  48772. this.setValue(currentValue, -1);
  48773. };
  48774. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  48775. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  48776. this._ratioOffset = this._previousRatio - newRatio;
  48777. };
  48778. /**
  48779. * Execute the current animation
  48780. * @param delay defines the delay to add to the current frame
  48781. * @param from defines the lower bound of the animation range
  48782. * @param to defines the upper bound of the animation range
  48783. * @param loop defines if the current animation must loop
  48784. * @param speedRatio defines the current speed ratio
  48785. * @param weight defines the weight of the animation (default is -1 so no weight)
  48786. * @returns a boolean indicating if the animation has ended
  48787. */
  48788. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48789. if (weight === void 0) { weight = -1.0; }
  48790. var targetPropertyPath = this._animation.targetPropertyPath;
  48791. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48792. this._stopped = true;
  48793. return false;
  48794. }
  48795. var returnValue = true;
  48796. var keys = this._animation.getKeys();
  48797. // Adding a start key at frame 0 if missing
  48798. if (keys[0].frame !== 0) {
  48799. var newKey = { frame: 0, value: keys[0].value };
  48800. keys.splice(0, 0, newKey);
  48801. }
  48802. // Check limits
  48803. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48804. from = keys[0].frame;
  48805. }
  48806. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48807. to = keys[keys.length - 1].frame;
  48808. }
  48809. //to and from cannot be the same key
  48810. if (from === to) {
  48811. if (from > keys[0].frame) {
  48812. from--;
  48813. }
  48814. else if (to < keys[keys.length - 1].frame) {
  48815. to++;
  48816. }
  48817. }
  48818. // Compute ratio
  48819. var range = to - from;
  48820. var offsetValue;
  48821. // ratio represents the frame delta between from and to
  48822. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48823. var highLimitValue = 0;
  48824. this._previousDelay = delay;
  48825. this._previousRatio = ratio;
  48826. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48827. returnValue = false;
  48828. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48829. }
  48830. else {
  48831. // Get max value if required
  48832. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48833. var keyOffset = to.toString() + from.toString();
  48834. if (!this._offsetsCache[keyOffset]) {
  48835. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48836. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48837. switch (this._animation.dataType) {
  48838. // Float
  48839. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48840. this._offsetsCache[keyOffset] = toValue - fromValue;
  48841. break;
  48842. // Quaternion
  48843. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48845. break;
  48846. // Vector3
  48847. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48848. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48849. // Vector2
  48850. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48851. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48852. // Size
  48853. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48854. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48855. // Color3
  48856. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48857. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48858. default:
  48859. break;
  48860. }
  48861. this._highLimitsCache[keyOffset] = toValue;
  48862. }
  48863. highLimitValue = this._highLimitsCache[keyOffset];
  48864. offsetValue = this._offsetsCache[keyOffset];
  48865. }
  48866. }
  48867. if (offsetValue === undefined) {
  48868. switch (this._animation.dataType) {
  48869. // Float
  48870. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48871. offsetValue = 0;
  48872. break;
  48873. // Quaternion
  48874. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48875. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48876. break;
  48877. // Vector3
  48878. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48879. offsetValue = BABYLON.Vector3.Zero();
  48880. break;
  48881. // Vector2
  48882. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48883. offsetValue = BABYLON.Vector2.Zero();
  48884. break;
  48885. // Size
  48886. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48887. offsetValue = BABYLON.Size.Zero();
  48888. break;
  48889. // Color3
  48890. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48891. offsetValue = BABYLON.Color3.Black();
  48892. }
  48893. }
  48894. // Compute value
  48895. var repeatCount = (ratio / range) >> 0;
  48896. var currentFrame = returnValue ? from + ratio % range : to;
  48897. // Need to normalize?
  48898. if (this._host && this._host.syncRoot) {
  48899. var syncRoot = this._host.syncRoot;
  48900. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48901. currentFrame = from + (to - from) * hostNormalizedFrame;
  48902. }
  48903. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48904. // Set value
  48905. this.setValue(currentValue, weight);
  48906. // Check events
  48907. var events = this._animation.getEvents();
  48908. for (var index = 0; index < events.length; index++) {
  48909. // Make sure current frame has passed event frame and that event frame is within the current range
  48910. // Also, handle both forward and reverse animations
  48911. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48912. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48913. var event = events[index];
  48914. if (!event.isDone) {
  48915. // If event should be done only once, remove it.
  48916. if (event.onlyOnce) {
  48917. events.splice(index, 1);
  48918. index--;
  48919. }
  48920. event.isDone = true;
  48921. event.action();
  48922. } // Don't do anything if the event has already be done.
  48923. }
  48924. else if (events[index].isDone && !events[index].onlyOnce) {
  48925. // reset event, the animation is looping
  48926. events[index].isDone = false;
  48927. }
  48928. }
  48929. if (!returnValue) {
  48930. this._stopped = true;
  48931. }
  48932. return returnValue;
  48933. };
  48934. return RuntimeAnimation;
  48935. }());
  48936. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48937. })(BABYLON || (BABYLON = {}));
  48938. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48939. "use strict";
  48940. var BABYLON;
  48941. (function (BABYLON) {
  48942. var Animatable = /** @class */ (function () {
  48943. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48944. if (fromFrame === void 0) { fromFrame = 0; }
  48945. if (toFrame === void 0) { toFrame = 100; }
  48946. if (loopAnimation === void 0) { loopAnimation = false; }
  48947. if (speedRatio === void 0) { speedRatio = 1.0; }
  48948. this.target = target;
  48949. this.fromFrame = fromFrame;
  48950. this.toFrame = toFrame;
  48951. this.loopAnimation = loopAnimation;
  48952. this.onAnimationEnd = onAnimationEnd;
  48953. this._localDelayOffset = null;
  48954. this._pausedDelay = null;
  48955. this._runtimeAnimations = new Array();
  48956. this._paused = false;
  48957. this._speedRatio = 1;
  48958. this._weight = -1.0;
  48959. this.animationStarted = false;
  48960. if (animations) {
  48961. this.appendAnimations(target, animations);
  48962. }
  48963. this._speedRatio = speedRatio;
  48964. this._scene = scene;
  48965. scene._activeAnimatables.push(this);
  48966. }
  48967. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48968. /**
  48969. * Gets the root Animatable used to synchronize and normalize animations
  48970. */
  48971. get: function () {
  48972. return this._syncRoot;
  48973. },
  48974. enumerable: true,
  48975. configurable: true
  48976. });
  48977. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48978. /**
  48979. * Gets the current frame of the first RuntimeAnimation
  48980. * Used to synchronize Animatables
  48981. */
  48982. get: function () {
  48983. if (this._runtimeAnimations.length === 0) {
  48984. return 0;
  48985. }
  48986. return this._runtimeAnimations[0].currentFrame;
  48987. },
  48988. enumerable: true,
  48989. configurable: true
  48990. });
  48991. Object.defineProperty(Animatable.prototype, "weight", {
  48992. /**
  48993. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48994. */
  48995. get: function () {
  48996. return this._weight;
  48997. },
  48998. set: function (value) {
  48999. if (value === -1) {
  49000. this._weight = -1;
  49001. return;
  49002. }
  49003. // Else weight must be in [0, 1] range
  49004. this._weight = Math.min(Math.max(value, 0), 1.0);
  49005. },
  49006. enumerable: true,
  49007. configurable: true
  49008. });
  49009. Object.defineProperty(Animatable.prototype, "speedRatio", {
  49010. /**
  49011. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  49012. */
  49013. get: function () {
  49014. return this._speedRatio;
  49015. },
  49016. set: function (value) {
  49017. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  49018. var animation = this._runtimeAnimations[index];
  49019. animation._prepareForSpeedRatioChange(value);
  49020. }
  49021. this._speedRatio = value;
  49022. },
  49023. enumerable: true,
  49024. configurable: true
  49025. });
  49026. // Methods
  49027. /**
  49028. * Synchronize and normalize current Animatable with a source Animatable.
  49029. * This is useful when using animation weights and when animations are not of the same length
  49030. * @param root defines the root Animatable to synchronize with
  49031. * @returns the current Animatable
  49032. */
  49033. Animatable.prototype.syncWith = function (root) {
  49034. this._syncRoot = root;
  49035. if (root) {
  49036. // Make sure this animatable will animate after the root
  49037. var index = this._scene._activeAnimatables.indexOf(this);
  49038. if (index > -1) {
  49039. this._scene._activeAnimatables.splice(index, 1);
  49040. this._scene._activeAnimatables.push(this);
  49041. }
  49042. }
  49043. return this;
  49044. };
  49045. Animatable.prototype.getAnimations = function () {
  49046. return this._runtimeAnimations;
  49047. };
  49048. Animatable.prototype.appendAnimations = function (target, animations) {
  49049. for (var index = 0; index < animations.length; index++) {
  49050. var animation = animations[index];
  49051. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  49052. }
  49053. };
  49054. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  49055. var runtimeAnimations = this._runtimeAnimations;
  49056. for (var index = 0; index < runtimeAnimations.length; index++) {
  49057. if (runtimeAnimations[index].animation.targetProperty === property) {
  49058. return runtimeAnimations[index].animation;
  49059. }
  49060. }
  49061. return null;
  49062. };
  49063. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  49064. var runtimeAnimations = this._runtimeAnimations;
  49065. for (var index = 0; index < runtimeAnimations.length; index++) {
  49066. if (runtimeAnimations[index].animation.targetProperty === property) {
  49067. return runtimeAnimations[index];
  49068. }
  49069. }
  49070. return null;
  49071. };
  49072. Animatable.prototype.reset = function () {
  49073. var runtimeAnimations = this._runtimeAnimations;
  49074. for (var index = 0; index < runtimeAnimations.length; index++) {
  49075. runtimeAnimations[index].reset();
  49076. }
  49077. // Reset to original value
  49078. for (index = 0; index < runtimeAnimations.length; index++) {
  49079. var animation = runtimeAnimations[index];
  49080. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  49081. }
  49082. this._localDelayOffset = null;
  49083. this._pausedDelay = null;
  49084. };
  49085. Animatable.prototype.enableBlending = function (blendingSpeed) {
  49086. var runtimeAnimations = this._runtimeAnimations;
  49087. for (var index = 0; index < runtimeAnimations.length; index++) {
  49088. runtimeAnimations[index].animation.enableBlending = true;
  49089. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  49090. }
  49091. };
  49092. Animatable.prototype.disableBlending = function () {
  49093. var runtimeAnimations = this._runtimeAnimations;
  49094. for (var index = 0; index < runtimeAnimations.length; index++) {
  49095. runtimeAnimations[index].animation.enableBlending = false;
  49096. }
  49097. };
  49098. Animatable.prototype.goToFrame = function (frame) {
  49099. var runtimeAnimations = this._runtimeAnimations;
  49100. if (runtimeAnimations[0]) {
  49101. var fps = runtimeAnimations[0].animation.framePerSecond;
  49102. var currentFrame = runtimeAnimations[0].currentFrame;
  49103. var adjustTime = frame - currentFrame;
  49104. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  49105. if (this._localDelayOffset === null) {
  49106. this._localDelayOffset = 0;
  49107. }
  49108. this._localDelayOffset -= delay;
  49109. }
  49110. for (var index = 0; index < runtimeAnimations.length; index++) {
  49111. runtimeAnimations[index].goToFrame(frame);
  49112. }
  49113. };
  49114. Animatable.prototype.pause = function () {
  49115. if (this._paused) {
  49116. return;
  49117. }
  49118. this._paused = true;
  49119. };
  49120. Animatable.prototype.restart = function () {
  49121. this._paused = false;
  49122. };
  49123. Animatable.prototype.stop = function (animationName) {
  49124. if (animationName) {
  49125. var idx = this._scene._activeAnimatables.indexOf(this);
  49126. if (idx > -1) {
  49127. var runtimeAnimations = this._runtimeAnimations;
  49128. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  49129. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  49130. continue;
  49131. }
  49132. runtimeAnimations[index].dispose();
  49133. runtimeAnimations.splice(index, 1);
  49134. }
  49135. if (runtimeAnimations.length == 0) {
  49136. this._scene._activeAnimatables.splice(idx, 1);
  49137. if (this.onAnimationEnd) {
  49138. this.onAnimationEnd();
  49139. }
  49140. }
  49141. }
  49142. }
  49143. else {
  49144. var index = this._scene._activeAnimatables.indexOf(this);
  49145. if (index > -1) {
  49146. this._scene._activeAnimatables.splice(index, 1);
  49147. var runtimeAnimations = this._runtimeAnimations;
  49148. for (var index = 0; index < runtimeAnimations.length; index++) {
  49149. runtimeAnimations[index].dispose();
  49150. }
  49151. if (this.onAnimationEnd) {
  49152. this.onAnimationEnd();
  49153. }
  49154. }
  49155. }
  49156. };
  49157. Animatable.prototype._animate = function (delay) {
  49158. if (this._paused) {
  49159. this.animationStarted = false;
  49160. if (this._pausedDelay === null) {
  49161. this._pausedDelay = delay;
  49162. }
  49163. return true;
  49164. }
  49165. if (this._localDelayOffset === null) {
  49166. this._localDelayOffset = delay;
  49167. this._pausedDelay = null;
  49168. }
  49169. else if (this._pausedDelay !== null) {
  49170. this._localDelayOffset += delay - this._pausedDelay;
  49171. this._pausedDelay = null;
  49172. }
  49173. if (this._weight === 0) {
  49174. return true;
  49175. }
  49176. // Animating
  49177. var running = false;
  49178. var runtimeAnimations = this._runtimeAnimations;
  49179. var index;
  49180. for (index = 0; index < runtimeAnimations.length; index++) {
  49181. var animation = runtimeAnimations[index];
  49182. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  49183. running = running || isRunning;
  49184. }
  49185. this.animationStarted = running;
  49186. if (!running) {
  49187. // Remove from active animatables
  49188. index = this._scene._activeAnimatables.indexOf(this);
  49189. this._scene._activeAnimatables.splice(index, 1);
  49190. // Dispose all runtime animations
  49191. for (index = 0; index < runtimeAnimations.length; index++) {
  49192. runtimeAnimations[index].dispose();
  49193. }
  49194. }
  49195. if (!running && this.onAnimationEnd) {
  49196. this.onAnimationEnd();
  49197. this.onAnimationEnd = null;
  49198. }
  49199. return running;
  49200. };
  49201. return Animatable;
  49202. }());
  49203. BABYLON.Animatable = Animatable;
  49204. })(BABYLON || (BABYLON = {}));
  49205. //# sourceMappingURL=babylon.animatable.js.map
  49206. "use strict";
  49207. var BABYLON;
  49208. (function (BABYLON) {
  49209. var EasingFunction = /** @class */ (function () {
  49210. function EasingFunction() {
  49211. // Properties
  49212. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  49213. }
  49214. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  49215. get: function () {
  49216. return EasingFunction._EASINGMODE_EASEIN;
  49217. },
  49218. enumerable: true,
  49219. configurable: true
  49220. });
  49221. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  49222. get: function () {
  49223. return EasingFunction._EASINGMODE_EASEOUT;
  49224. },
  49225. enumerable: true,
  49226. configurable: true
  49227. });
  49228. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  49229. get: function () {
  49230. return EasingFunction._EASINGMODE_EASEINOUT;
  49231. },
  49232. enumerable: true,
  49233. configurable: true
  49234. });
  49235. EasingFunction.prototype.setEasingMode = function (easingMode) {
  49236. var n = Math.min(Math.max(easingMode, 0), 2);
  49237. this._easingMode = n;
  49238. };
  49239. EasingFunction.prototype.getEasingMode = function () {
  49240. return this._easingMode;
  49241. };
  49242. EasingFunction.prototype.easeInCore = function (gradient) {
  49243. throw new Error('You must implement this method');
  49244. };
  49245. EasingFunction.prototype.ease = function (gradient) {
  49246. switch (this._easingMode) {
  49247. case EasingFunction.EASINGMODE_EASEIN:
  49248. return this.easeInCore(gradient);
  49249. case EasingFunction.EASINGMODE_EASEOUT:
  49250. return (1 - this.easeInCore(1 - gradient));
  49251. }
  49252. if (gradient >= 0.5) {
  49253. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  49254. }
  49255. return (this.easeInCore(gradient * 2) * 0.5);
  49256. };
  49257. //Statics
  49258. EasingFunction._EASINGMODE_EASEIN = 0;
  49259. EasingFunction._EASINGMODE_EASEOUT = 1;
  49260. EasingFunction._EASINGMODE_EASEINOUT = 2;
  49261. return EasingFunction;
  49262. }());
  49263. BABYLON.EasingFunction = EasingFunction;
  49264. var CircleEase = /** @class */ (function (_super) {
  49265. __extends(CircleEase, _super);
  49266. function CircleEase() {
  49267. return _super !== null && _super.apply(this, arguments) || this;
  49268. }
  49269. CircleEase.prototype.easeInCore = function (gradient) {
  49270. gradient = Math.max(0, Math.min(1, gradient));
  49271. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  49272. };
  49273. return CircleEase;
  49274. }(EasingFunction));
  49275. BABYLON.CircleEase = CircleEase;
  49276. var BackEase = /** @class */ (function (_super) {
  49277. __extends(BackEase, _super);
  49278. function BackEase(amplitude) {
  49279. if (amplitude === void 0) { amplitude = 1; }
  49280. var _this = _super.call(this) || this;
  49281. _this.amplitude = amplitude;
  49282. return _this;
  49283. }
  49284. BackEase.prototype.easeInCore = function (gradient) {
  49285. var num = Math.max(0, this.amplitude);
  49286. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  49287. };
  49288. return BackEase;
  49289. }(EasingFunction));
  49290. BABYLON.BackEase = BackEase;
  49291. var BounceEase = /** @class */ (function (_super) {
  49292. __extends(BounceEase, _super);
  49293. function BounceEase(bounces, bounciness) {
  49294. if (bounces === void 0) { bounces = 3; }
  49295. if (bounciness === void 0) { bounciness = 2; }
  49296. var _this = _super.call(this) || this;
  49297. _this.bounces = bounces;
  49298. _this.bounciness = bounciness;
  49299. return _this;
  49300. }
  49301. BounceEase.prototype.easeInCore = function (gradient) {
  49302. var y = Math.max(0.0, this.bounces);
  49303. var bounciness = this.bounciness;
  49304. if (bounciness <= 1.0) {
  49305. bounciness = 1.001;
  49306. }
  49307. var num9 = Math.pow(bounciness, y);
  49308. var num5 = 1.0 - bounciness;
  49309. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  49310. var num15 = gradient * num4;
  49311. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  49312. var num3 = Math.floor(num65);
  49313. var num13 = num3 + 1.0;
  49314. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  49315. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  49316. var num7 = (num8 + num12) * 0.5;
  49317. var num6 = gradient - num7;
  49318. var num2 = num7 - num8;
  49319. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  49320. };
  49321. return BounceEase;
  49322. }(EasingFunction));
  49323. BABYLON.BounceEase = BounceEase;
  49324. var CubicEase = /** @class */ (function (_super) {
  49325. __extends(CubicEase, _super);
  49326. function CubicEase() {
  49327. return _super !== null && _super.apply(this, arguments) || this;
  49328. }
  49329. CubicEase.prototype.easeInCore = function (gradient) {
  49330. return (gradient * gradient * gradient);
  49331. };
  49332. return CubicEase;
  49333. }(EasingFunction));
  49334. BABYLON.CubicEase = CubicEase;
  49335. var ElasticEase = /** @class */ (function (_super) {
  49336. __extends(ElasticEase, _super);
  49337. function ElasticEase(oscillations, springiness) {
  49338. if (oscillations === void 0) { oscillations = 3; }
  49339. if (springiness === void 0) { springiness = 3; }
  49340. var _this = _super.call(this) || this;
  49341. _this.oscillations = oscillations;
  49342. _this.springiness = springiness;
  49343. return _this;
  49344. }
  49345. ElasticEase.prototype.easeInCore = function (gradient) {
  49346. var num2;
  49347. var num3 = Math.max(0.0, this.oscillations);
  49348. var num = Math.max(0.0, this.springiness);
  49349. if (num == 0) {
  49350. num2 = gradient;
  49351. }
  49352. else {
  49353. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  49354. }
  49355. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  49356. };
  49357. return ElasticEase;
  49358. }(EasingFunction));
  49359. BABYLON.ElasticEase = ElasticEase;
  49360. var ExponentialEase = /** @class */ (function (_super) {
  49361. __extends(ExponentialEase, _super);
  49362. function ExponentialEase(exponent) {
  49363. if (exponent === void 0) { exponent = 2; }
  49364. var _this = _super.call(this) || this;
  49365. _this.exponent = exponent;
  49366. return _this;
  49367. }
  49368. ExponentialEase.prototype.easeInCore = function (gradient) {
  49369. if (this.exponent <= 0) {
  49370. return gradient;
  49371. }
  49372. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  49373. };
  49374. return ExponentialEase;
  49375. }(EasingFunction));
  49376. BABYLON.ExponentialEase = ExponentialEase;
  49377. var PowerEase = /** @class */ (function (_super) {
  49378. __extends(PowerEase, _super);
  49379. function PowerEase(power) {
  49380. if (power === void 0) { power = 2; }
  49381. var _this = _super.call(this) || this;
  49382. _this.power = power;
  49383. return _this;
  49384. }
  49385. PowerEase.prototype.easeInCore = function (gradient) {
  49386. var y = Math.max(0.0, this.power);
  49387. return Math.pow(gradient, y);
  49388. };
  49389. return PowerEase;
  49390. }(EasingFunction));
  49391. BABYLON.PowerEase = PowerEase;
  49392. var QuadraticEase = /** @class */ (function (_super) {
  49393. __extends(QuadraticEase, _super);
  49394. function QuadraticEase() {
  49395. return _super !== null && _super.apply(this, arguments) || this;
  49396. }
  49397. QuadraticEase.prototype.easeInCore = function (gradient) {
  49398. return (gradient * gradient);
  49399. };
  49400. return QuadraticEase;
  49401. }(EasingFunction));
  49402. BABYLON.QuadraticEase = QuadraticEase;
  49403. var QuarticEase = /** @class */ (function (_super) {
  49404. __extends(QuarticEase, _super);
  49405. function QuarticEase() {
  49406. return _super !== null && _super.apply(this, arguments) || this;
  49407. }
  49408. QuarticEase.prototype.easeInCore = function (gradient) {
  49409. return (gradient * gradient * gradient * gradient);
  49410. };
  49411. return QuarticEase;
  49412. }(EasingFunction));
  49413. BABYLON.QuarticEase = QuarticEase;
  49414. var QuinticEase = /** @class */ (function (_super) {
  49415. __extends(QuinticEase, _super);
  49416. function QuinticEase() {
  49417. return _super !== null && _super.apply(this, arguments) || this;
  49418. }
  49419. QuinticEase.prototype.easeInCore = function (gradient) {
  49420. return (gradient * gradient * gradient * gradient * gradient);
  49421. };
  49422. return QuinticEase;
  49423. }(EasingFunction));
  49424. BABYLON.QuinticEase = QuinticEase;
  49425. var SineEase = /** @class */ (function (_super) {
  49426. __extends(SineEase, _super);
  49427. function SineEase() {
  49428. return _super !== null && _super.apply(this, arguments) || this;
  49429. }
  49430. SineEase.prototype.easeInCore = function (gradient) {
  49431. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  49432. };
  49433. return SineEase;
  49434. }(EasingFunction));
  49435. BABYLON.SineEase = SineEase;
  49436. var BezierCurveEase = /** @class */ (function (_super) {
  49437. __extends(BezierCurveEase, _super);
  49438. function BezierCurveEase(x1, y1, x2, y2) {
  49439. if (x1 === void 0) { x1 = 0; }
  49440. if (y1 === void 0) { y1 = 0; }
  49441. if (x2 === void 0) { x2 = 1; }
  49442. if (y2 === void 0) { y2 = 1; }
  49443. var _this = _super.call(this) || this;
  49444. _this.x1 = x1;
  49445. _this.y1 = y1;
  49446. _this.x2 = x2;
  49447. _this.y2 = y2;
  49448. return _this;
  49449. }
  49450. BezierCurveEase.prototype.easeInCore = function (gradient) {
  49451. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  49452. };
  49453. return BezierCurveEase;
  49454. }(EasingFunction));
  49455. BABYLON.BezierCurveEase = BezierCurveEase;
  49456. })(BABYLON || (BABYLON = {}));
  49457. //# sourceMappingURL=babylon.easing.js.map
  49458. "use strict";
  49459. var BABYLON;
  49460. (function (BABYLON) {
  49461. /**
  49462. * A Condition applied to an Action
  49463. */
  49464. var Condition = /** @class */ (function () {
  49465. /**
  49466. * Creates a new Condition
  49467. * @param actionManager the manager of the action the condition is applied to
  49468. */
  49469. function Condition(actionManager) {
  49470. this._actionManager = actionManager;
  49471. }
  49472. /**
  49473. * Check if the current condition is valid
  49474. * @returns a boolean
  49475. */
  49476. Condition.prototype.isValid = function () {
  49477. return true;
  49478. };
  49479. /**
  49480. * Internal only
  49481. * @ignore
  49482. */
  49483. Condition.prototype._getProperty = function (propertyPath) {
  49484. return this._actionManager._getProperty(propertyPath);
  49485. };
  49486. /**
  49487. * Internal only
  49488. * @ignore
  49489. */
  49490. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  49491. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49492. };
  49493. /**
  49494. * Serialize placeholder for child classes
  49495. * @returns the serialized object
  49496. */
  49497. Condition.prototype.serialize = function () {
  49498. };
  49499. /**
  49500. * Internal only
  49501. * @ignore
  49502. */
  49503. Condition.prototype._serialize = function (serializedCondition) {
  49504. return {
  49505. type: 2,
  49506. children: [],
  49507. name: serializedCondition.name,
  49508. properties: serializedCondition.properties
  49509. };
  49510. };
  49511. return Condition;
  49512. }());
  49513. BABYLON.Condition = Condition;
  49514. /**
  49515. * Defines specific conditional operators as extensions of Condition
  49516. */
  49517. var ValueCondition = /** @class */ (function (_super) {
  49518. __extends(ValueCondition, _super);
  49519. /**
  49520. * Creates a new ValueCondition
  49521. * @param actionManager manager for the action the condition applies to
  49522. * @param target for the action
  49523. * @param propertyPath path to specify the property of the target the conditional operator uses
  49524. * @param value the vale compared by the conditional operator against the current value of the property
  49525. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  49526. */
  49527. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  49528. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  49529. var _this = _super.call(this, actionManager) || this;
  49530. _this.propertyPath = propertyPath;
  49531. _this.value = value;
  49532. _this.operator = operator;
  49533. _this._target = target;
  49534. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  49535. _this._property = _this._getProperty(_this.propertyPath);
  49536. return _this;
  49537. }
  49538. Object.defineProperty(ValueCondition, "IsEqual", {
  49539. /**
  49540. * returns the number for IsEqual
  49541. */
  49542. get: function () {
  49543. return ValueCondition._IsEqual;
  49544. },
  49545. enumerable: true,
  49546. configurable: true
  49547. });
  49548. Object.defineProperty(ValueCondition, "IsDifferent", {
  49549. /**
  49550. * Returns the number for IsDifferent
  49551. */
  49552. get: function () {
  49553. return ValueCondition._IsDifferent;
  49554. },
  49555. enumerable: true,
  49556. configurable: true
  49557. });
  49558. Object.defineProperty(ValueCondition, "IsGreater", {
  49559. /**
  49560. * Returns the number for IsGreater
  49561. */
  49562. get: function () {
  49563. return ValueCondition._IsGreater;
  49564. },
  49565. enumerable: true,
  49566. configurable: true
  49567. });
  49568. Object.defineProperty(ValueCondition, "IsLesser", {
  49569. /**
  49570. * Returns the number for IsLesser
  49571. */
  49572. get: function () {
  49573. return ValueCondition._IsLesser;
  49574. },
  49575. enumerable: true,
  49576. configurable: true
  49577. });
  49578. /**
  49579. * Compares the given value with the property value for the specified conditional operator
  49580. * @returns the result of the comparison
  49581. */
  49582. ValueCondition.prototype.isValid = function () {
  49583. switch (this.operator) {
  49584. case ValueCondition.IsGreater:
  49585. return this._effectiveTarget[this._property] > this.value;
  49586. case ValueCondition.IsLesser:
  49587. return this._effectiveTarget[this._property] < this.value;
  49588. case ValueCondition.IsEqual:
  49589. case ValueCondition.IsDifferent:
  49590. var check;
  49591. if (this.value.equals) {
  49592. check = this.value.equals(this._effectiveTarget[this._property]);
  49593. }
  49594. else {
  49595. check = this.value === this._effectiveTarget[this._property];
  49596. }
  49597. return this.operator === ValueCondition.IsEqual ? check : !check;
  49598. }
  49599. return false;
  49600. };
  49601. /**
  49602. * Serialize the ValueCondition into a JSON compatible object
  49603. * @returns serialization object
  49604. */
  49605. ValueCondition.prototype.serialize = function () {
  49606. return this._serialize({
  49607. name: "ValueCondition",
  49608. properties: [
  49609. BABYLON.Action._GetTargetProperty(this._target),
  49610. { name: "propertyPath", value: this.propertyPath },
  49611. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49612. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  49613. ]
  49614. });
  49615. };
  49616. /**
  49617. * Gets the name of the conditional operator for the ValueCondition
  49618. * @param operator the conditional operator
  49619. * @returns the name
  49620. */
  49621. ValueCondition.GetOperatorName = function (operator) {
  49622. switch (operator) {
  49623. case ValueCondition._IsEqual: return "IsEqual";
  49624. case ValueCondition._IsDifferent: return "IsDifferent";
  49625. case ValueCondition._IsGreater: return "IsGreater";
  49626. case ValueCondition._IsLesser: return "IsLesser";
  49627. default: return "";
  49628. }
  49629. };
  49630. /**
  49631. * Internal only
  49632. * @ignore
  49633. */
  49634. ValueCondition._IsEqual = 0;
  49635. /**
  49636. * Internal only
  49637. * @ignore
  49638. */
  49639. ValueCondition._IsDifferent = 1;
  49640. /**
  49641. * Internal only
  49642. * @ignore
  49643. */
  49644. ValueCondition._IsGreater = 2;
  49645. /**
  49646. * Internal only
  49647. * @ignore
  49648. */
  49649. ValueCondition._IsLesser = 3;
  49650. return ValueCondition;
  49651. }(Condition));
  49652. BABYLON.ValueCondition = ValueCondition;
  49653. /**
  49654. * Defines a predicate condition as an extension of Condition
  49655. */
  49656. var PredicateCondition = /** @class */ (function (_super) {
  49657. __extends(PredicateCondition, _super);
  49658. /**
  49659. * Creates a new {BABYLON.PredicateCondition}
  49660. * @param actionManager manager for the action the condition applies to
  49661. * @param predicate
  49662. */
  49663. function PredicateCondition(actionManager, predicate) {
  49664. var _this = _super.call(this, actionManager) || this;
  49665. _this.predicate = predicate;
  49666. return _this;
  49667. }
  49668. /**
  49669. * @returns the validity of the predicate condition
  49670. */
  49671. PredicateCondition.prototype.isValid = function () {
  49672. return this.predicate();
  49673. };
  49674. return PredicateCondition;
  49675. }(Condition));
  49676. BABYLON.PredicateCondition = PredicateCondition;
  49677. /**
  49678. * Defines a state condition as an extension of {BABYLON.Condition}
  49679. */
  49680. var StateCondition = /** @class */ (function (_super) {
  49681. __extends(StateCondition, _super);
  49682. /**
  49683. * Creates a new {BABYLON.StateCondition}
  49684. * @param actionManager manager for the action the condition applies to
  49685. * @param target of the condition
  49686. * @param value to compare with target state
  49687. */
  49688. function StateCondition(actionManager, target, value) {
  49689. var _this = _super.call(this, actionManager) || this;
  49690. _this.value = value;
  49691. _this._target = target;
  49692. return _this;
  49693. }
  49694. /**
  49695. * @returns the validity of the state
  49696. */
  49697. StateCondition.prototype.isValid = function () {
  49698. return this._target.state === this.value;
  49699. };
  49700. /**
  49701. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  49702. * @returns serialization object
  49703. */
  49704. StateCondition.prototype.serialize = function () {
  49705. return this._serialize({
  49706. name: "StateCondition",
  49707. properties: [
  49708. BABYLON.Action._GetTargetProperty(this._target),
  49709. { name: "value", value: this.value }
  49710. ]
  49711. });
  49712. };
  49713. return StateCondition;
  49714. }(Condition));
  49715. BABYLON.StateCondition = StateCondition;
  49716. })(BABYLON || (BABYLON = {}));
  49717. //# sourceMappingURL=babylon.condition.js.map
  49718. "use strict";
  49719. var BABYLON;
  49720. (function (BABYLON) {
  49721. /**
  49722. * The action to be carried out following a trigger
  49723. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  49724. */
  49725. var Action = /** @class */ (function () {
  49726. /**
  49727. * Creates a new Action
  49728. * @param triggerOptions the trigger, with or without parameters, for the action
  49729. * @param condition an optional determinant of action
  49730. */
  49731. function Action(triggerOptions, condition) {
  49732. this.triggerOptions = triggerOptions;
  49733. /**
  49734. * An event triggered prior to action being executed.
  49735. */
  49736. this.onBeforeExecuteObservable = new BABYLON.Observable();
  49737. if (triggerOptions.parameter) {
  49738. this.trigger = triggerOptions.trigger;
  49739. this._triggerParameter = triggerOptions.parameter;
  49740. }
  49741. else {
  49742. this.trigger = triggerOptions;
  49743. }
  49744. this._nextActiveAction = this;
  49745. this._condition = condition;
  49746. }
  49747. /**
  49748. * Internal only
  49749. * @ignore
  49750. */
  49751. Action.prototype._prepare = function () {
  49752. };
  49753. /**
  49754. * Gets the trigger parameters
  49755. * @returns the trigger parameters
  49756. */
  49757. Action.prototype.getTriggerParameter = function () {
  49758. return this._triggerParameter;
  49759. };
  49760. /**
  49761. * Internal only - executes current action event
  49762. * @ignore
  49763. */
  49764. Action.prototype._executeCurrent = function (evt) {
  49765. if (this._nextActiveAction._condition) {
  49766. var condition = this._nextActiveAction._condition;
  49767. var currentRenderId = this._actionManager.getScene().getRenderId();
  49768. // We cache the current evaluation for the current frame
  49769. if (condition._evaluationId === currentRenderId) {
  49770. if (!condition._currentResult) {
  49771. return;
  49772. }
  49773. }
  49774. else {
  49775. condition._evaluationId = currentRenderId;
  49776. if (!condition.isValid()) {
  49777. condition._currentResult = false;
  49778. return;
  49779. }
  49780. condition._currentResult = true;
  49781. }
  49782. }
  49783. this.onBeforeExecuteObservable.notifyObservers(this);
  49784. this._nextActiveAction.execute(evt);
  49785. this.skipToNextActiveAction();
  49786. };
  49787. /**
  49788. * Execute placeholder for child classes
  49789. * @param evt optional action event
  49790. */
  49791. Action.prototype.execute = function (evt) {
  49792. };
  49793. /**
  49794. * Skips to next active action
  49795. */
  49796. Action.prototype.skipToNextActiveAction = function () {
  49797. if (this._nextActiveAction._child) {
  49798. if (!this._nextActiveAction._child._actionManager) {
  49799. this._nextActiveAction._child._actionManager = this._actionManager;
  49800. }
  49801. this._nextActiveAction = this._nextActiveAction._child;
  49802. }
  49803. else {
  49804. this._nextActiveAction = this;
  49805. }
  49806. };
  49807. /**
  49808. * Adds action to chain of actions, may be a DoNothingAction
  49809. * @param index The index of the attribute.
  49810. * @returns The action passed in
  49811. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49812. */
  49813. Action.prototype.then = function (action) {
  49814. this._child = action;
  49815. action._actionManager = this._actionManager;
  49816. action._prepare();
  49817. return action;
  49818. };
  49819. /**
  49820. * Internal only
  49821. * @ignore
  49822. */
  49823. Action.prototype._getProperty = function (propertyPath) {
  49824. return this._actionManager._getProperty(propertyPath);
  49825. };
  49826. /**
  49827. * Internal only
  49828. * @ignore
  49829. */
  49830. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49831. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49832. };
  49833. /**
  49834. * Serialize placeholder for child classes
  49835. * @param parent of child
  49836. * @returns the serialized object
  49837. */
  49838. Action.prototype.serialize = function (parent) {
  49839. };
  49840. /**
  49841. * Internal only called by serialize
  49842. * @ignore
  49843. */
  49844. Action.prototype._serialize = function (serializedAction, parent) {
  49845. var serializationObject = {
  49846. type: 1,
  49847. children: [],
  49848. name: serializedAction.name,
  49849. properties: serializedAction.properties || []
  49850. };
  49851. // Serialize child
  49852. if (this._child) {
  49853. this._child.serialize(serializationObject);
  49854. }
  49855. // Check if "this" has a condition
  49856. if (this._condition) {
  49857. var serializedCondition = this._condition.serialize();
  49858. serializedCondition.children.push(serializationObject);
  49859. if (parent) {
  49860. parent.children.push(serializedCondition);
  49861. }
  49862. return serializedCondition;
  49863. }
  49864. if (parent) {
  49865. parent.children.push(serializationObject);
  49866. }
  49867. return serializationObject;
  49868. };
  49869. /**
  49870. * Internal only
  49871. * @ignore
  49872. */
  49873. Action._SerializeValueAsString = function (value) {
  49874. if (typeof value === "number") {
  49875. return value.toString();
  49876. }
  49877. if (typeof value === "boolean") {
  49878. return value ? "true" : "false";
  49879. }
  49880. if (value instanceof BABYLON.Vector2) {
  49881. return value.x + ", " + value.y;
  49882. }
  49883. if (value instanceof BABYLON.Vector3) {
  49884. return value.x + ", " + value.y + ", " + value.z;
  49885. }
  49886. if (value instanceof BABYLON.Color3) {
  49887. return value.r + ", " + value.g + ", " + value.b;
  49888. }
  49889. if (value instanceof BABYLON.Color4) {
  49890. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49891. }
  49892. return value; // string
  49893. };
  49894. /**
  49895. * Internal only
  49896. * @ignore
  49897. */
  49898. Action._GetTargetProperty = function (target) {
  49899. return {
  49900. name: "target",
  49901. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49902. : target instanceof BABYLON.Light ? "LightProperties"
  49903. : target instanceof BABYLON.Camera ? "CameraProperties"
  49904. : "SceneProperties",
  49905. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49906. };
  49907. };
  49908. return Action;
  49909. }());
  49910. BABYLON.Action = Action;
  49911. })(BABYLON || (BABYLON = {}));
  49912. //# sourceMappingURL=babylon.action.js.map
  49913. "use strict";
  49914. var BABYLON;
  49915. (function (BABYLON) {
  49916. /**
  49917. * ActionEvent is the event being sent when an action is triggered.
  49918. */
  49919. var ActionEvent = /** @class */ (function () {
  49920. /**
  49921. * @param source The mesh or sprite that triggered the action.
  49922. * @param pointerX The X mouse cursor position at the time of the event
  49923. * @param pointerY The Y mouse cursor position at the time of the event
  49924. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49925. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49926. */
  49927. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49928. this.source = source;
  49929. this.pointerX = pointerX;
  49930. this.pointerY = pointerY;
  49931. this.meshUnderPointer = meshUnderPointer;
  49932. this.sourceEvent = sourceEvent;
  49933. this.additionalData = additionalData;
  49934. }
  49935. /**
  49936. * Helper function to auto-create an ActionEvent from a source mesh.
  49937. * @param source The source mesh that triggered the event
  49938. * @param evt {Event} The original (browser) event
  49939. */
  49940. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49941. var scene = source.getScene();
  49942. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49943. };
  49944. /**
  49945. * Helper function to auto-create an ActionEvent from a source mesh.
  49946. * @param source The source sprite that triggered the event
  49947. * @param scene Scene associated with the sprite
  49948. * @param evt {Event} The original (browser) event
  49949. */
  49950. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49951. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49952. };
  49953. /**
  49954. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49955. * @param scene the scene where the event occurred
  49956. * @param evt {Event} The original (browser) event
  49957. */
  49958. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49959. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49960. };
  49961. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49962. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49963. };
  49964. return ActionEvent;
  49965. }());
  49966. BABYLON.ActionEvent = ActionEvent;
  49967. /**
  49968. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49969. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49970. */
  49971. var ActionManager = /** @class */ (function () {
  49972. function ActionManager(scene) {
  49973. // Members
  49974. this.actions = new Array();
  49975. this.hoverCursor = '';
  49976. this._scene = scene;
  49977. scene._actionManagers.push(this);
  49978. }
  49979. Object.defineProperty(ActionManager, "NothingTrigger", {
  49980. get: function () {
  49981. return ActionManager._NothingTrigger;
  49982. },
  49983. enumerable: true,
  49984. configurable: true
  49985. });
  49986. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49987. get: function () {
  49988. return ActionManager._OnPickTrigger;
  49989. },
  49990. enumerable: true,
  49991. configurable: true
  49992. });
  49993. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49994. get: function () {
  49995. return ActionManager._OnLeftPickTrigger;
  49996. },
  49997. enumerable: true,
  49998. configurable: true
  49999. });
  50000. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  50001. get: function () {
  50002. return ActionManager._OnRightPickTrigger;
  50003. },
  50004. enumerable: true,
  50005. configurable: true
  50006. });
  50007. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  50008. get: function () {
  50009. return ActionManager._OnCenterPickTrigger;
  50010. },
  50011. enumerable: true,
  50012. configurable: true
  50013. });
  50014. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  50015. get: function () {
  50016. return ActionManager._OnPickDownTrigger;
  50017. },
  50018. enumerable: true,
  50019. configurable: true
  50020. });
  50021. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  50022. get: function () {
  50023. return ActionManager._OnDoublePickTrigger;
  50024. },
  50025. enumerable: true,
  50026. configurable: true
  50027. });
  50028. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  50029. get: function () {
  50030. return ActionManager._OnPickUpTrigger;
  50031. },
  50032. enumerable: true,
  50033. configurable: true
  50034. });
  50035. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  50036. /// This trigger will only be raised if you also declared a OnPickDown
  50037. get: function () {
  50038. return ActionManager._OnPickOutTrigger;
  50039. },
  50040. enumerable: true,
  50041. configurable: true
  50042. });
  50043. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  50044. get: function () {
  50045. return ActionManager._OnLongPressTrigger;
  50046. },
  50047. enumerable: true,
  50048. configurable: true
  50049. });
  50050. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  50051. get: function () {
  50052. return ActionManager._OnPointerOverTrigger;
  50053. },
  50054. enumerable: true,
  50055. configurable: true
  50056. });
  50057. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  50058. get: function () {
  50059. return ActionManager._OnPointerOutTrigger;
  50060. },
  50061. enumerable: true,
  50062. configurable: true
  50063. });
  50064. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  50065. get: function () {
  50066. return ActionManager._OnEveryFrameTrigger;
  50067. },
  50068. enumerable: true,
  50069. configurable: true
  50070. });
  50071. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  50072. get: function () {
  50073. return ActionManager._OnIntersectionEnterTrigger;
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  50079. get: function () {
  50080. return ActionManager._OnIntersectionExitTrigger;
  50081. },
  50082. enumerable: true,
  50083. configurable: true
  50084. });
  50085. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  50086. get: function () {
  50087. return ActionManager._OnKeyDownTrigger;
  50088. },
  50089. enumerable: true,
  50090. configurable: true
  50091. });
  50092. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  50093. get: function () {
  50094. return ActionManager._OnKeyUpTrigger;
  50095. },
  50096. enumerable: true,
  50097. configurable: true
  50098. });
  50099. // Methods
  50100. ActionManager.prototype.dispose = function () {
  50101. var index = this._scene._actionManagers.indexOf(this);
  50102. for (var i = 0; i < this.actions.length; i++) {
  50103. var action = this.actions[i];
  50104. ActionManager.Triggers[action.trigger]--;
  50105. if (ActionManager.Triggers[action.trigger] === 0) {
  50106. delete ActionManager.Triggers[action.trigger];
  50107. }
  50108. }
  50109. if (index > -1) {
  50110. this._scene._actionManagers.splice(index, 1);
  50111. }
  50112. };
  50113. ActionManager.prototype.getScene = function () {
  50114. return this._scene;
  50115. };
  50116. /**
  50117. * Does this action manager handles actions of any of the given triggers
  50118. * @param {number[]} triggers - the triggers to be tested
  50119. * @return {boolean} whether one (or more) of the triggers is handeled
  50120. */
  50121. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  50122. for (var index = 0; index < this.actions.length; index++) {
  50123. var action = this.actions[index];
  50124. if (triggers.indexOf(action.trigger) > -1) {
  50125. return true;
  50126. }
  50127. }
  50128. return false;
  50129. };
  50130. /**
  50131. * Does this action manager handles actions of a given trigger
  50132. * @param {number} trigger - the trigger to be tested
  50133. * @return {boolean} whether the trigger is handeled
  50134. */
  50135. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  50136. for (var index = 0; index < this.actions.length; index++) {
  50137. var action = this.actions[index];
  50138. if (action.trigger === trigger) {
  50139. return true;
  50140. }
  50141. }
  50142. return false;
  50143. };
  50144. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  50145. /**
  50146. * Does this action manager has pointer triggers
  50147. * @return {boolean} whether or not it has pointer triggers
  50148. */
  50149. get: function () {
  50150. for (var index = 0; index < this.actions.length; index++) {
  50151. var action = this.actions[index];
  50152. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  50153. return true;
  50154. }
  50155. }
  50156. return false;
  50157. },
  50158. enumerable: true,
  50159. configurable: true
  50160. });
  50161. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  50162. /**
  50163. * Does this action manager has pick triggers
  50164. * @return {boolean} whether or not it has pick triggers
  50165. */
  50166. get: function () {
  50167. for (var index = 0; index < this.actions.length; index++) {
  50168. var action = this.actions[index];
  50169. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  50170. return true;
  50171. }
  50172. }
  50173. return false;
  50174. },
  50175. enumerable: true,
  50176. configurable: true
  50177. });
  50178. Object.defineProperty(ActionManager, "HasTriggers", {
  50179. /**
  50180. * Does exist one action manager with at least one trigger
  50181. * @return {boolean} whether or not it exists one action manager with one trigger
  50182. **/
  50183. get: function () {
  50184. for (var t in ActionManager.Triggers) {
  50185. if (ActionManager.Triggers.hasOwnProperty(t)) {
  50186. return true;
  50187. }
  50188. }
  50189. return false;
  50190. },
  50191. enumerable: true,
  50192. configurable: true
  50193. });
  50194. Object.defineProperty(ActionManager, "HasPickTriggers", {
  50195. /**
  50196. * Does exist one action manager with at least one pick trigger
  50197. * @return {boolean} whether or not it exists one action manager with one pick trigger
  50198. **/
  50199. get: function () {
  50200. for (var t in ActionManager.Triggers) {
  50201. if (ActionManager.Triggers.hasOwnProperty(t)) {
  50202. var t_int = parseInt(t);
  50203. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  50204. return true;
  50205. }
  50206. }
  50207. }
  50208. return false;
  50209. },
  50210. enumerable: true,
  50211. configurable: true
  50212. });
  50213. /**
  50214. * Does exist one action manager that handles actions of a given trigger
  50215. * @param {number} trigger - the trigger to be tested
  50216. * @return {boolean} whether the trigger is handeled by at least one action manager
  50217. **/
  50218. ActionManager.HasSpecificTrigger = function (trigger) {
  50219. for (var t in ActionManager.Triggers) {
  50220. if (ActionManager.Triggers.hasOwnProperty(t)) {
  50221. var t_int = parseInt(t);
  50222. if (t_int === trigger) {
  50223. return true;
  50224. }
  50225. }
  50226. }
  50227. return false;
  50228. };
  50229. /**
  50230. * Registers an action to this action manager
  50231. * @param {BABYLON.Action} action - the action to be registered
  50232. * @return {BABYLON.Action} the action amended (prepared) after registration
  50233. */
  50234. ActionManager.prototype.registerAction = function (action) {
  50235. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  50236. if (this.getScene().actionManager !== this) {
  50237. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  50238. return null;
  50239. }
  50240. }
  50241. this.actions.push(action);
  50242. if (ActionManager.Triggers[action.trigger]) {
  50243. ActionManager.Triggers[action.trigger]++;
  50244. }
  50245. else {
  50246. ActionManager.Triggers[action.trigger] = 1;
  50247. }
  50248. action._actionManager = this;
  50249. action._prepare();
  50250. return action;
  50251. };
  50252. /**
  50253. * Unregisters an action to this action manager
  50254. * @param action The action to be unregistered
  50255. * @return whether the action has been unregistered
  50256. */
  50257. ActionManager.prototype.unregisterAction = function (action) {
  50258. var index = this.actions.indexOf(action);
  50259. if (index !== -1) {
  50260. this.actions.splice(index, 1);
  50261. ActionManager.Triggers[action.trigger] -= 1;
  50262. if (ActionManager.Triggers[action.trigger] === 0) {
  50263. delete ActionManager.Triggers[action.trigger];
  50264. }
  50265. delete action._actionManager;
  50266. return true;
  50267. }
  50268. return false;
  50269. };
  50270. /**
  50271. * Process a specific trigger
  50272. * @param {number} trigger - the trigger to process
  50273. * @param evt {BABYLON.ActionEvent} the event details to be processed
  50274. */
  50275. ActionManager.prototype.processTrigger = function (trigger, evt) {
  50276. for (var index = 0; index < this.actions.length; index++) {
  50277. var action = this.actions[index];
  50278. if (action.trigger === trigger) {
  50279. if (evt) {
  50280. if (trigger === ActionManager.OnKeyUpTrigger
  50281. || trigger === ActionManager.OnKeyDownTrigger) {
  50282. var parameter = action.getTriggerParameter();
  50283. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  50284. if (!parameter.toLowerCase) {
  50285. continue;
  50286. }
  50287. var lowerCase = parameter.toLowerCase();
  50288. if (lowerCase !== evt.sourceEvent.key) {
  50289. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  50290. var actualkey = String.fromCharCode(unicode).toLowerCase();
  50291. if (actualkey !== lowerCase) {
  50292. continue;
  50293. }
  50294. }
  50295. }
  50296. }
  50297. }
  50298. action._executeCurrent(evt);
  50299. }
  50300. }
  50301. };
  50302. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  50303. var properties = propertyPath.split(".");
  50304. for (var index = 0; index < properties.length - 1; index++) {
  50305. target = target[properties[index]];
  50306. }
  50307. return target;
  50308. };
  50309. ActionManager.prototype._getProperty = function (propertyPath) {
  50310. var properties = propertyPath.split(".");
  50311. return properties[properties.length - 1];
  50312. };
  50313. ActionManager.prototype.serialize = function (name) {
  50314. var root = {
  50315. children: new Array(),
  50316. name: name,
  50317. type: 3,
  50318. properties: new Array() // Empty for root but required
  50319. };
  50320. for (var i = 0; i < this.actions.length; i++) {
  50321. var triggerObject = {
  50322. type: 0,
  50323. children: new Array(),
  50324. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  50325. properties: new Array()
  50326. };
  50327. var triggerOptions = this.actions[i].triggerOptions;
  50328. if (triggerOptions && typeof triggerOptions !== "number") {
  50329. if (triggerOptions.parameter instanceof BABYLON.Node) {
  50330. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  50331. }
  50332. else {
  50333. var parameter = {};
  50334. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  50335. if (triggerOptions.parameter.mesh) {
  50336. parameter._meshId = triggerOptions.parameter.mesh.id;
  50337. }
  50338. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  50339. }
  50340. }
  50341. // Serialize child action, recursively
  50342. this.actions[i].serialize(triggerObject);
  50343. // Add serialized trigger
  50344. root.children.push(triggerObject);
  50345. }
  50346. return root;
  50347. };
  50348. ActionManager.Parse = function (parsedActions, object, scene) {
  50349. var actionManager = new ActionManager(scene);
  50350. if (object === null)
  50351. scene.actionManager = actionManager;
  50352. else
  50353. object.actionManager = actionManager;
  50354. // instanciate a new object
  50355. var instanciate = function (name, params) {
  50356. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  50357. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  50358. newInstance.constructor.apply(newInstance, params);
  50359. return newInstance;
  50360. };
  50361. var parseParameter = function (name, value, target, propertyPath) {
  50362. if (propertyPath === null) {
  50363. // String, boolean or float
  50364. var floatValue = parseFloat(value);
  50365. if (value === "true" || value === "false")
  50366. return value === "true";
  50367. else
  50368. return isNaN(floatValue) ? value : floatValue;
  50369. }
  50370. var effectiveTarget = propertyPath.split(".");
  50371. var values = value.split(",");
  50372. // Get effective Target
  50373. for (var i = 0; i < effectiveTarget.length; i++) {
  50374. target = target[effectiveTarget[i]];
  50375. }
  50376. // Return appropriate value with its type
  50377. if (typeof (target) === "boolean")
  50378. return values[0] === "true";
  50379. if (typeof (target) === "string")
  50380. return values[0];
  50381. // Parameters with multiple values such as Vector3 etc.
  50382. var split = new Array();
  50383. for (var i = 0; i < values.length; i++)
  50384. split.push(parseFloat(values[i]));
  50385. if (target instanceof BABYLON.Vector3)
  50386. return BABYLON.Vector3.FromArray(split);
  50387. if (target instanceof BABYLON.Vector4)
  50388. return BABYLON.Vector4.FromArray(split);
  50389. if (target instanceof BABYLON.Color3)
  50390. return BABYLON.Color3.FromArray(split);
  50391. if (target instanceof BABYLON.Color4)
  50392. return BABYLON.Color4.FromArray(split);
  50393. return parseFloat(values[0]);
  50394. };
  50395. // traverse graph per trigger
  50396. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  50397. if (combineArray === void 0) { combineArray = null; }
  50398. if (parsedAction.detached)
  50399. return;
  50400. var parameters = new Array();
  50401. var target = null;
  50402. var propertyPath = null;
  50403. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  50404. // Parameters
  50405. if (parsedAction.type === 2)
  50406. parameters.push(actionManager);
  50407. else
  50408. parameters.push(trigger);
  50409. if (combine) {
  50410. var actions = new Array();
  50411. for (var j = 0; j < parsedAction.combine.length; j++) {
  50412. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  50413. }
  50414. parameters.push(actions);
  50415. }
  50416. else {
  50417. for (var i = 0; i < parsedAction.properties.length; i++) {
  50418. var value = parsedAction.properties[i].value;
  50419. var name = parsedAction.properties[i].name;
  50420. var targetType = parsedAction.properties[i].targetType;
  50421. if (name === "target")
  50422. if (targetType !== null && targetType === "SceneProperties")
  50423. value = target = scene;
  50424. else
  50425. value = target = scene.getNodeByName(value);
  50426. else if (name === "parent")
  50427. value = scene.getNodeByName(value);
  50428. else if (name === "sound")
  50429. value = scene.getSoundByName(value);
  50430. else if (name !== "propertyPath") {
  50431. if (parsedAction.type === 2 && name === "operator")
  50432. value = BABYLON.ValueCondition[value];
  50433. else
  50434. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  50435. }
  50436. else {
  50437. propertyPath = value;
  50438. }
  50439. parameters.push(value);
  50440. }
  50441. }
  50442. if (combineArray === null) {
  50443. parameters.push(condition);
  50444. }
  50445. else {
  50446. parameters.push(null);
  50447. }
  50448. // If interpolate value action
  50449. if (parsedAction.name === "InterpolateValueAction") {
  50450. var param = parameters[parameters.length - 2];
  50451. parameters[parameters.length - 1] = param;
  50452. parameters[parameters.length - 2] = condition;
  50453. }
  50454. // Action or condition(s) and not CombineAction
  50455. var newAction = instanciate(parsedAction.name, parameters);
  50456. if (newAction instanceof BABYLON.Condition && condition !== null) {
  50457. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  50458. if (action)
  50459. action.then(nothing);
  50460. else
  50461. actionManager.registerAction(nothing);
  50462. action = nothing;
  50463. }
  50464. if (combineArray === null) {
  50465. if (newAction instanceof BABYLON.Condition) {
  50466. condition = newAction;
  50467. newAction = action;
  50468. }
  50469. else {
  50470. condition = null;
  50471. if (action)
  50472. action.then(newAction);
  50473. else
  50474. actionManager.registerAction(newAction);
  50475. }
  50476. }
  50477. else {
  50478. combineArray.push(newAction);
  50479. }
  50480. for (var i = 0; i < parsedAction.children.length; i++)
  50481. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  50482. };
  50483. // triggers
  50484. for (var i = 0; i < parsedActions.children.length; i++) {
  50485. var triggerParams;
  50486. var trigger = parsedActions.children[i];
  50487. if (trigger.properties.length > 0) {
  50488. var param = trigger.properties[0].value;
  50489. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  50490. if (value._meshId) {
  50491. value.mesh = scene.getMeshByID(value._meshId);
  50492. }
  50493. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  50494. }
  50495. else
  50496. triggerParams = ActionManager[trigger.name];
  50497. for (var j = 0; j < trigger.children.length; j++) {
  50498. if (!trigger.detached)
  50499. traverse(trigger.children[j], triggerParams, null, null);
  50500. }
  50501. }
  50502. };
  50503. ActionManager.GetTriggerName = function (trigger) {
  50504. switch (trigger) {
  50505. case 0: return "NothingTrigger";
  50506. case 1: return "OnPickTrigger";
  50507. case 2: return "OnLeftPickTrigger";
  50508. case 3: return "OnRightPickTrigger";
  50509. case 4: return "OnCenterPickTrigger";
  50510. case 5: return "OnPickDownTrigger";
  50511. case 6: return "OnPickUpTrigger";
  50512. case 7: return "OnLongPressTrigger";
  50513. case 8: return "OnPointerOverTrigger";
  50514. case 9: return "OnPointerOutTrigger";
  50515. case 10: return "OnEveryFrameTrigger";
  50516. case 11: return "OnIntersectionEnterTrigger";
  50517. case 12: return "OnIntersectionExitTrigger";
  50518. case 13: return "OnKeyDownTrigger";
  50519. case 14: return "OnKeyUpTrigger";
  50520. case 15: return "OnPickOutTrigger";
  50521. default: return "";
  50522. }
  50523. };
  50524. // Statics
  50525. ActionManager._NothingTrigger = 0;
  50526. ActionManager._OnPickTrigger = 1;
  50527. ActionManager._OnLeftPickTrigger = 2;
  50528. ActionManager._OnRightPickTrigger = 3;
  50529. ActionManager._OnCenterPickTrigger = 4;
  50530. ActionManager._OnPickDownTrigger = 5;
  50531. ActionManager._OnDoublePickTrigger = 6;
  50532. ActionManager._OnPickUpTrigger = 7;
  50533. ActionManager._OnLongPressTrigger = 8;
  50534. ActionManager._OnPointerOverTrigger = 9;
  50535. ActionManager._OnPointerOutTrigger = 10;
  50536. ActionManager._OnEveryFrameTrigger = 11;
  50537. ActionManager._OnIntersectionEnterTrigger = 12;
  50538. ActionManager._OnIntersectionExitTrigger = 13;
  50539. ActionManager._OnKeyDownTrigger = 14;
  50540. ActionManager._OnKeyUpTrigger = 15;
  50541. ActionManager._OnPickOutTrigger = 16;
  50542. ActionManager.Triggers = {};
  50543. return ActionManager;
  50544. }());
  50545. BABYLON.ActionManager = ActionManager;
  50546. })(BABYLON || (BABYLON = {}));
  50547. //# sourceMappingURL=babylon.actionManager.js.map
  50548. "use strict";
  50549. var BABYLON;
  50550. (function (BABYLON) {
  50551. var InterpolateValueAction = /** @class */ (function (_super) {
  50552. __extends(InterpolateValueAction, _super);
  50553. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  50554. if (duration === void 0) { duration = 1000; }
  50555. var _this = _super.call(this, triggerOptions, condition) || this;
  50556. _this.propertyPath = propertyPath;
  50557. _this.value = value;
  50558. _this.duration = duration;
  50559. _this.stopOtherAnimations = stopOtherAnimations;
  50560. _this.onInterpolationDone = onInterpolationDone;
  50561. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  50562. _this._target = _this._effectiveTarget = target;
  50563. return _this;
  50564. }
  50565. InterpolateValueAction.prototype._prepare = function () {
  50566. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50567. this._property = this._getProperty(this.propertyPath);
  50568. };
  50569. InterpolateValueAction.prototype.execute = function () {
  50570. var _this = this;
  50571. var scene = this._actionManager.getScene();
  50572. var keys = [
  50573. {
  50574. frame: 0,
  50575. value: this._effectiveTarget[this._property]
  50576. }, {
  50577. frame: 100,
  50578. value: this.value
  50579. }
  50580. ];
  50581. var dataType;
  50582. if (typeof this.value === "number") {
  50583. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  50584. }
  50585. else if (this.value instanceof BABYLON.Color3) {
  50586. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  50587. }
  50588. else if (this.value instanceof BABYLON.Vector3) {
  50589. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  50590. }
  50591. else if (this.value instanceof BABYLON.Matrix) {
  50592. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  50593. }
  50594. else if (this.value instanceof BABYLON.Quaternion) {
  50595. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  50596. }
  50597. else {
  50598. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  50599. return;
  50600. }
  50601. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  50602. animation.setKeys(keys);
  50603. if (this.stopOtherAnimations) {
  50604. scene.stopAnimation(this._effectiveTarget);
  50605. }
  50606. var wrapper = function () {
  50607. _this.onInterpolationDoneObservable.notifyObservers(_this);
  50608. if (_this.onInterpolationDone) {
  50609. _this.onInterpolationDone();
  50610. }
  50611. };
  50612. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  50613. };
  50614. InterpolateValueAction.prototype.serialize = function (parent) {
  50615. return _super.prototype._serialize.call(this, {
  50616. name: "InterpolateValueAction",
  50617. properties: [
  50618. BABYLON.Action._GetTargetProperty(this._target),
  50619. { name: "propertyPath", value: this.propertyPath },
  50620. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  50621. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  50622. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  50623. ]
  50624. }, parent);
  50625. };
  50626. return InterpolateValueAction;
  50627. }(BABYLON.Action));
  50628. BABYLON.InterpolateValueAction = InterpolateValueAction;
  50629. })(BABYLON || (BABYLON = {}));
  50630. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  50631. "use strict";
  50632. var BABYLON;
  50633. (function (BABYLON) {
  50634. var SwitchBooleanAction = /** @class */ (function (_super) {
  50635. __extends(SwitchBooleanAction, _super);
  50636. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  50637. var _this = _super.call(this, triggerOptions, condition) || this;
  50638. _this.propertyPath = propertyPath;
  50639. _this._target = _this._effectiveTarget = target;
  50640. return _this;
  50641. }
  50642. SwitchBooleanAction.prototype._prepare = function () {
  50643. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50644. this._property = this._getProperty(this.propertyPath);
  50645. };
  50646. SwitchBooleanAction.prototype.execute = function () {
  50647. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  50648. };
  50649. SwitchBooleanAction.prototype.serialize = function (parent) {
  50650. return _super.prototype._serialize.call(this, {
  50651. name: "SwitchBooleanAction",
  50652. properties: [
  50653. BABYLON.Action._GetTargetProperty(this._target),
  50654. { name: "propertyPath", value: this.propertyPath }
  50655. ]
  50656. }, parent);
  50657. };
  50658. return SwitchBooleanAction;
  50659. }(BABYLON.Action));
  50660. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  50661. var SetStateAction = /** @class */ (function (_super) {
  50662. __extends(SetStateAction, _super);
  50663. function SetStateAction(triggerOptions, target, value, condition) {
  50664. var _this = _super.call(this, triggerOptions, condition) || this;
  50665. _this.value = value;
  50666. _this._target = target;
  50667. return _this;
  50668. }
  50669. SetStateAction.prototype.execute = function () {
  50670. this._target.state = this.value;
  50671. };
  50672. SetStateAction.prototype.serialize = function (parent) {
  50673. return _super.prototype._serialize.call(this, {
  50674. name: "SetStateAction",
  50675. properties: [
  50676. BABYLON.Action._GetTargetProperty(this._target),
  50677. { name: "value", value: this.value }
  50678. ]
  50679. }, parent);
  50680. };
  50681. return SetStateAction;
  50682. }(BABYLON.Action));
  50683. BABYLON.SetStateAction = SetStateAction;
  50684. var SetValueAction = /** @class */ (function (_super) {
  50685. __extends(SetValueAction, _super);
  50686. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  50687. var _this = _super.call(this, triggerOptions, condition) || this;
  50688. _this.propertyPath = propertyPath;
  50689. _this.value = value;
  50690. _this._target = _this._effectiveTarget = target;
  50691. return _this;
  50692. }
  50693. SetValueAction.prototype._prepare = function () {
  50694. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50695. this._property = this._getProperty(this.propertyPath);
  50696. };
  50697. SetValueAction.prototype.execute = function () {
  50698. this._effectiveTarget[this._property] = this.value;
  50699. if (this._target.markAsDirty) {
  50700. this._target.markAsDirty(this._property);
  50701. }
  50702. };
  50703. SetValueAction.prototype.serialize = function (parent) {
  50704. return _super.prototype._serialize.call(this, {
  50705. name: "SetValueAction",
  50706. properties: [
  50707. BABYLON.Action._GetTargetProperty(this._target),
  50708. { name: "propertyPath", value: this.propertyPath },
  50709. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50710. ]
  50711. }, parent);
  50712. };
  50713. return SetValueAction;
  50714. }(BABYLON.Action));
  50715. BABYLON.SetValueAction = SetValueAction;
  50716. var IncrementValueAction = /** @class */ (function (_super) {
  50717. __extends(IncrementValueAction, _super);
  50718. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  50719. var _this = _super.call(this, triggerOptions, condition) || this;
  50720. _this.propertyPath = propertyPath;
  50721. _this.value = value;
  50722. _this._target = _this._effectiveTarget = target;
  50723. return _this;
  50724. }
  50725. IncrementValueAction.prototype._prepare = function () {
  50726. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  50727. this._property = this._getProperty(this.propertyPath);
  50728. if (typeof this._effectiveTarget[this._property] !== "number") {
  50729. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  50730. }
  50731. };
  50732. IncrementValueAction.prototype.execute = function () {
  50733. this._effectiveTarget[this._property] += this.value;
  50734. if (this._target.markAsDirty) {
  50735. this._target.markAsDirty(this._property);
  50736. }
  50737. };
  50738. IncrementValueAction.prototype.serialize = function (parent) {
  50739. return _super.prototype._serialize.call(this, {
  50740. name: "IncrementValueAction",
  50741. properties: [
  50742. BABYLON.Action._GetTargetProperty(this._target),
  50743. { name: "propertyPath", value: this.propertyPath },
  50744. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  50745. ]
  50746. }, parent);
  50747. };
  50748. return IncrementValueAction;
  50749. }(BABYLON.Action));
  50750. BABYLON.IncrementValueAction = IncrementValueAction;
  50751. var PlayAnimationAction = /** @class */ (function (_super) {
  50752. __extends(PlayAnimationAction, _super);
  50753. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  50754. var _this = _super.call(this, triggerOptions, condition) || this;
  50755. _this.from = from;
  50756. _this.to = to;
  50757. _this.loop = loop;
  50758. _this._target = target;
  50759. return _this;
  50760. }
  50761. PlayAnimationAction.prototype._prepare = function () {
  50762. };
  50763. PlayAnimationAction.prototype.execute = function () {
  50764. var scene = this._actionManager.getScene();
  50765. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  50766. };
  50767. PlayAnimationAction.prototype.serialize = function (parent) {
  50768. return _super.prototype._serialize.call(this, {
  50769. name: "PlayAnimationAction",
  50770. properties: [
  50771. BABYLON.Action._GetTargetProperty(this._target),
  50772. { name: "from", value: String(this.from) },
  50773. { name: "to", value: String(this.to) },
  50774. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  50775. ]
  50776. }, parent);
  50777. };
  50778. return PlayAnimationAction;
  50779. }(BABYLON.Action));
  50780. BABYLON.PlayAnimationAction = PlayAnimationAction;
  50781. var StopAnimationAction = /** @class */ (function (_super) {
  50782. __extends(StopAnimationAction, _super);
  50783. function StopAnimationAction(triggerOptions, target, condition) {
  50784. var _this = _super.call(this, triggerOptions, condition) || this;
  50785. _this._target = target;
  50786. return _this;
  50787. }
  50788. StopAnimationAction.prototype._prepare = function () {
  50789. };
  50790. StopAnimationAction.prototype.execute = function () {
  50791. var scene = this._actionManager.getScene();
  50792. scene.stopAnimation(this._target);
  50793. };
  50794. StopAnimationAction.prototype.serialize = function (parent) {
  50795. return _super.prototype._serialize.call(this, {
  50796. name: "StopAnimationAction",
  50797. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50798. }, parent);
  50799. };
  50800. return StopAnimationAction;
  50801. }(BABYLON.Action));
  50802. BABYLON.StopAnimationAction = StopAnimationAction;
  50803. var DoNothingAction = /** @class */ (function (_super) {
  50804. __extends(DoNothingAction, _super);
  50805. function DoNothingAction(triggerOptions, condition) {
  50806. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50807. return _super.call(this, triggerOptions, condition) || this;
  50808. }
  50809. DoNothingAction.prototype.execute = function () {
  50810. };
  50811. DoNothingAction.prototype.serialize = function (parent) {
  50812. return _super.prototype._serialize.call(this, {
  50813. name: "DoNothingAction",
  50814. properties: []
  50815. }, parent);
  50816. };
  50817. return DoNothingAction;
  50818. }(BABYLON.Action));
  50819. BABYLON.DoNothingAction = DoNothingAction;
  50820. var CombineAction = /** @class */ (function (_super) {
  50821. __extends(CombineAction, _super);
  50822. function CombineAction(triggerOptions, children, condition) {
  50823. var _this = _super.call(this, triggerOptions, condition) || this;
  50824. _this.children = children;
  50825. return _this;
  50826. }
  50827. CombineAction.prototype._prepare = function () {
  50828. for (var index = 0; index < this.children.length; index++) {
  50829. this.children[index]._actionManager = this._actionManager;
  50830. this.children[index]._prepare();
  50831. }
  50832. };
  50833. CombineAction.prototype.execute = function (evt) {
  50834. for (var index = 0; index < this.children.length; index++) {
  50835. this.children[index].execute(evt);
  50836. }
  50837. };
  50838. CombineAction.prototype.serialize = function (parent) {
  50839. var serializationObject = _super.prototype._serialize.call(this, {
  50840. name: "CombineAction",
  50841. properties: [],
  50842. combine: []
  50843. }, parent);
  50844. for (var i = 0; i < this.children.length; i++) {
  50845. serializationObject.combine.push(this.children[i].serialize(null));
  50846. }
  50847. return serializationObject;
  50848. };
  50849. return CombineAction;
  50850. }(BABYLON.Action));
  50851. BABYLON.CombineAction = CombineAction;
  50852. var ExecuteCodeAction = /** @class */ (function (_super) {
  50853. __extends(ExecuteCodeAction, _super);
  50854. function ExecuteCodeAction(triggerOptions, func, condition) {
  50855. var _this = _super.call(this, triggerOptions, condition) || this;
  50856. _this.func = func;
  50857. return _this;
  50858. }
  50859. ExecuteCodeAction.prototype.execute = function (evt) {
  50860. this.func(evt);
  50861. };
  50862. return ExecuteCodeAction;
  50863. }(BABYLON.Action));
  50864. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50865. var SetParentAction = /** @class */ (function (_super) {
  50866. __extends(SetParentAction, _super);
  50867. function SetParentAction(triggerOptions, target, parent, condition) {
  50868. var _this = _super.call(this, triggerOptions, condition) || this;
  50869. _this._target = target;
  50870. _this._parent = parent;
  50871. return _this;
  50872. }
  50873. SetParentAction.prototype._prepare = function () {
  50874. };
  50875. SetParentAction.prototype.execute = function () {
  50876. if (this._target.parent === this._parent) {
  50877. return;
  50878. }
  50879. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50880. invertParentWorldMatrix.invert();
  50881. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50882. this._target.parent = this._parent;
  50883. };
  50884. SetParentAction.prototype.serialize = function (parent) {
  50885. return _super.prototype._serialize.call(this, {
  50886. name: "SetParentAction",
  50887. properties: [
  50888. BABYLON.Action._GetTargetProperty(this._target),
  50889. BABYLON.Action._GetTargetProperty(this._parent),
  50890. ]
  50891. }, parent);
  50892. };
  50893. return SetParentAction;
  50894. }(BABYLON.Action));
  50895. BABYLON.SetParentAction = SetParentAction;
  50896. var PlaySoundAction = /** @class */ (function (_super) {
  50897. __extends(PlaySoundAction, _super);
  50898. function PlaySoundAction(triggerOptions, sound, condition) {
  50899. var _this = _super.call(this, triggerOptions, condition) || this;
  50900. _this._sound = sound;
  50901. return _this;
  50902. }
  50903. PlaySoundAction.prototype._prepare = function () {
  50904. };
  50905. PlaySoundAction.prototype.execute = function () {
  50906. if (this._sound !== undefined)
  50907. this._sound.play();
  50908. };
  50909. PlaySoundAction.prototype.serialize = function (parent) {
  50910. return _super.prototype._serialize.call(this, {
  50911. name: "PlaySoundAction",
  50912. properties: [{ name: "sound", value: this._sound.name }]
  50913. }, parent);
  50914. };
  50915. return PlaySoundAction;
  50916. }(BABYLON.Action));
  50917. BABYLON.PlaySoundAction = PlaySoundAction;
  50918. var StopSoundAction = /** @class */ (function (_super) {
  50919. __extends(StopSoundAction, _super);
  50920. function StopSoundAction(triggerOptions, sound, condition) {
  50921. var _this = _super.call(this, triggerOptions, condition) || this;
  50922. _this._sound = sound;
  50923. return _this;
  50924. }
  50925. StopSoundAction.prototype._prepare = function () {
  50926. };
  50927. StopSoundAction.prototype.execute = function () {
  50928. if (this._sound !== undefined)
  50929. this._sound.stop();
  50930. };
  50931. StopSoundAction.prototype.serialize = function (parent) {
  50932. return _super.prototype._serialize.call(this, {
  50933. name: "StopSoundAction",
  50934. properties: [{ name: "sound", value: this._sound.name }]
  50935. }, parent);
  50936. };
  50937. return StopSoundAction;
  50938. }(BABYLON.Action));
  50939. BABYLON.StopSoundAction = StopSoundAction;
  50940. })(BABYLON || (BABYLON = {}));
  50941. //# sourceMappingURL=babylon.directActions.js.map
  50942. "use strict";
  50943. var BABYLON;
  50944. (function (BABYLON) {
  50945. var SpriteManager = /** @class */ (function () {
  50946. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50947. if (epsilon === void 0) { epsilon = 0.01; }
  50948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50949. this.name = name;
  50950. this.sprites = new Array();
  50951. this.renderingGroupId = 0;
  50952. this.layerMask = 0x0FFFFFFF;
  50953. this.fogEnabled = true;
  50954. this.isPickable = false;
  50955. /**
  50956. * An event triggered when the manager is disposed.
  50957. */
  50958. this.onDisposeObservable = new BABYLON.Observable();
  50959. this._vertexBuffers = {};
  50960. this._capacity = capacity;
  50961. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50962. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50963. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50964. if (cellSize.width && cellSize.height) {
  50965. this.cellWidth = cellSize.width;
  50966. this.cellHeight = cellSize.height;
  50967. }
  50968. else if (cellSize !== undefined) {
  50969. this.cellWidth = cellSize;
  50970. this.cellHeight = cellSize;
  50971. }
  50972. else {
  50973. return;
  50974. }
  50975. this._epsilon = epsilon;
  50976. this._scene = scene;
  50977. this._scene.spriteManagers.push(this);
  50978. var indices = [];
  50979. var index = 0;
  50980. for (var count = 0; count < capacity; count++) {
  50981. indices.push(index);
  50982. indices.push(index + 1);
  50983. indices.push(index + 2);
  50984. indices.push(index);
  50985. indices.push(index + 2);
  50986. indices.push(index + 3);
  50987. index += 4;
  50988. }
  50989. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50990. // VBO
  50991. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50992. this._vertexData = new Float32Array(capacity * 16 * 4);
  50993. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50994. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50995. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50996. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50997. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50998. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50999. this._vertexBuffers["options"] = options;
  51000. this._vertexBuffers["cellInfo"] = cellInfo;
  51001. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51002. // Effects
  51003. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  51004. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  51005. }
  51006. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  51007. set: function (callback) {
  51008. if (this._onDisposeObserver) {
  51009. this.onDisposeObservable.remove(this._onDisposeObserver);
  51010. }
  51011. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51012. },
  51013. enumerable: true,
  51014. configurable: true
  51015. });
  51016. Object.defineProperty(SpriteManager.prototype, "texture", {
  51017. get: function () {
  51018. return this._spriteTexture;
  51019. },
  51020. set: function (value) {
  51021. this._spriteTexture = value;
  51022. },
  51023. enumerable: true,
  51024. configurable: true
  51025. });
  51026. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  51027. var arrayOffset = index * 16;
  51028. if (offsetX === 0)
  51029. offsetX = this._epsilon;
  51030. else if (offsetX === 1)
  51031. offsetX = 1 - this._epsilon;
  51032. if (offsetY === 0)
  51033. offsetY = this._epsilon;
  51034. else if (offsetY === 1)
  51035. offsetY = 1 - this._epsilon;
  51036. this._vertexData[arrayOffset] = sprite.position.x;
  51037. this._vertexData[arrayOffset + 1] = sprite.position.y;
  51038. this._vertexData[arrayOffset + 2] = sprite.position.z;
  51039. this._vertexData[arrayOffset + 3] = sprite.angle;
  51040. this._vertexData[arrayOffset + 4] = sprite.width;
  51041. this._vertexData[arrayOffset + 5] = sprite.height;
  51042. this._vertexData[arrayOffset + 6] = offsetX;
  51043. this._vertexData[arrayOffset + 7] = offsetY;
  51044. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  51045. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  51046. var offset = (sprite.cellIndex / rowSize) >> 0;
  51047. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  51048. this._vertexData[arrayOffset + 11] = offset;
  51049. // Color
  51050. this._vertexData[arrayOffset + 12] = sprite.color.r;
  51051. this._vertexData[arrayOffset + 13] = sprite.color.g;
  51052. this._vertexData[arrayOffset + 14] = sprite.color.b;
  51053. this._vertexData[arrayOffset + 15] = sprite.color.a;
  51054. };
  51055. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  51056. var count = Math.min(this._capacity, this.sprites.length);
  51057. var min = BABYLON.Vector3.Zero();
  51058. var max = BABYLON.Vector3.Zero();
  51059. var distance = Number.MAX_VALUE;
  51060. var currentSprite = null;
  51061. var cameraSpacePosition = BABYLON.Vector3.Zero();
  51062. var cameraView = camera.getViewMatrix();
  51063. for (var index = 0; index < count; index++) {
  51064. var sprite = this.sprites[index];
  51065. if (!sprite) {
  51066. continue;
  51067. }
  51068. if (predicate) {
  51069. if (!predicate(sprite)) {
  51070. continue;
  51071. }
  51072. }
  51073. else if (!sprite.isPickable) {
  51074. continue;
  51075. }
  51076. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  51077. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  51078. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  51079. if (ray.intersectsBoxMinMax(min, max)) {
  51080. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  51081. if (distance > currentDistance) {
  51082. distance = currentDistance;
  51083. currentSprite = sprite;
  51084. if (fastCheck) {
  51085. break;
  51086. }
  51087. }
  51088. }
  51089. }
  51090. if (currentSprite) {
  51091. var result = new BABYLON.PickingInfo();
  51092. result.hit = true;
  51093. result.pickedSprite = currentSprite;
  51094. result.distance = distance;
  51095. return result;
  51096. }
  51097. return null;
  51098. };
  51099. SpriteManager.prototype.render = function () {
  51100. // Check
  51101. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  51102. return;
  51103. var engine = this._scene.getEngine();
  51104. var baseSize = this._spriteTexture.getBaseSize();
  51105. // Sprites
  51106. var deltaTime = engine.getDeltaTime();
  51107. var max = Math.min(this._capacity, this.sprites.length);
  51108. var rowSize = baseSize.width / this.cellWidth;
  51109. var offset = 0;
  51110. for (var index = 0; index < max; index++) {
  51111. var sprite = this.sprites[index];
  51112. if (!sprite) {
  51113. continue;
  51114. }
  51115. sprite._animate(deltaTime);
  51116. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  51117. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  51118. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  51119. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  51120. }
  51121. this._buffer.update(this._vertexData);
  51122. // Render
  51123. var effect = this._effectBase;
  51124. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51125. effect = this._effectFog;
  51126. }
  51127. engine.enableEffect(effect);
  51128. var viewMatrix = this._scene.getViewMatrix();
  51129. effect.setTexture("diffuseSampler", this._spriteTexture);
  51130. effect.setMatrix("view", viewMatrix);
  51131. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  51132. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  51133. // Fog
  51134. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51135. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  51136. effect.setColor3("vFogColor", this._scene.fogColor);
  51137. }
  51138. // VBOs
  51139. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  51140. // Draw order
  51141. engine.setDepthFunctionToLessOrEqual();
  51142. effect.setBool("alphaTest", true);
  51143. engine.setColorWrite(false);
  51144. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  51145. engine.setColorWrite(true);
  51146. effect.setBool("alphaTest", false);
  51147. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51148. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  51149. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51150. };
  51151. SpriteManager.prototype.dispose = function () {
  51152. if (this._buffer) {
  51153. this._buffer.dispose();
  51154. this._buffer = null;
  51155. }
  51156. if (this._indexBuffer) {
  51157. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  51158. this._indexBuffer = null;
  51159. }
  51160. if (this._spriteTexture) {
  51161. this._spriteTexture.dispose();
  51162. this._spriteTexture = null;
  51163. }
  51164. // Remove from scene
  51165. var index = this._scene.spriteManagers.indexOf(this);
  51166. this._scene.spriteManagers.splice(index, 1);
  51167. // Callback
  51168. this.onDisposeObservable.notifyObservers(this);
  51169. this.onDisposeObservable.clear();
  51170. };
  51171. return SpriteManager;
  51172. }());
  51173. BABYLON.SpriteManager = SpriteManager;
  51174. })(BABYLON || (BABYLON = {}));
  51175. //# sourceMappingURL=babylon.spriteManager.js.map
  51176. "use strict";
  51177. var BABYLON;
  51178. (function (BABYLON) {
  51179. var Sprite = /** @class */ (function () {
  51180. function Sprite(name, manager) {
  51181. this.name = name;
  51182. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51183. this.width = 1.0;
  51184. this.height = 1.0;
  51185. this.angle = 0;
  51186. this.cellIndex = 0;
  51187. this.invertU = 0;
  51188. this.invertV = 0;
  51189. this.animations = new Array();
  51190. this.isPickable = false;
  51191. this._animationStarted = false;
  51192. this._loopAnimation = false;
  51193. this._fromIndex = 0;
  51194. this._toIndex = 0;
  51195. this._delay = 0;
  51196. this._direction = 1;
  51197. this._time = 0;
  51198. this._manager = manager;
  51199. this._manager.sprites.push(this);
  51200. this.position = BABYLON.Vector3.Zero();
  51201. }
  51202. Object.defineProperty(Sprite.prototype, "size", {
  51203. get: function () {
  51204. return this.width;
  51205. },
  51206. set: function (value) {
  51207. this.width = value;
  51208. this.height = value;
  51209. },
  51210. enumerable: true,
  51211. configurable: true
  51212. });
  51213. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  51214. this._fromIndex = from;
  51215. this._toIndex = to;
  51216. this._loopAnimation = loop;
  51217. this._delay = delay;
  51218. this._animationStarted = true;
  51219. this._direction = from < to ? 1 : -1;
  51220. this.cellIndex = from;
  51221. this._time = 0;
  51222. this._onAnimationEnd = onAnimationEnd;
  51223. };
  51224. Sprite.prototype.stopAnimation = function () {
  51225. this._animationStarted = false;
  51226. };
  51227. Sprite.prototype._animate = function (deltaTime) {
  51228. if (!this._animationStarted)
  51229. return;
  51230. this._time += deltaTime;
  51231. if (this._time > this._delay) {
  51232. this._time = this._time % this._delay;
  51233. this.cellIndex += this._direction;
  51234. if (this.cellIndex > this._toIndex) {
  51235. if (this._loopAnimation) {
  51236. this.cellIndex = this._fromIndex;
  51237. }
  51238. else {
  51239. this.cellIndex = this._toIndex;
  51240. this._animationStarted = false;
  51241. if (this._onAnimationEnd) {
  51242. this._onAnimationEnd();
  51243. }
  51244. if (this.disposeWhenFinishedAnimating) {
  51245. this.dispose();
  51246. }
  51247. }
  51248. }
  51249. }
  51250. };
  51251. Sprite.prototype.dispose = function () {
  51252. for (var i = 0; i < this._manager.sprites.length; i++) {
  51253. if (this._manager.sprites[i] == this) {
  51254. this._manager.sprites.splice(i, 1);
  51255. }
  51256. }
  51257. };
  51258. return Sprite;
  51259. }());
  51260. BABYLON.Sprite = Sprite;
  51261. })(BABYLON || (BABYLON = {}));
  51262. //# sourceMappingURL=babylon.sprite.js.map
  51263. "use strict";
  51264. var BABYLON;
  51265. (function (BABYLON) {
  51266. var IntersectionInfo = /** @class */ (function () {
  51267. function IntersectionInfo(bu, bv, distance) {
  51268. this.bu = bu;
  51269. this.bv = bv;
  51270. this.distance = distance;
  51271. this.faceId = 0;
  51272. this.subMeshId = 0;
  51273. }
  51274. return IntersectionInfo;
  51275. }());
  51276. BABYLON.IntersectionInfo = IntersectionInfo;
  51277. var PickingInfo = /** @class */ (function () {
  51278. function PickingInfo() {
  51279. this.hit = false;
  51280. this.distance = 0;
  51281. this.pickedPoint = null;
  51282. this.pickedMesh = null;
  51283. this.bu = 0;
  51284. this.bv = 0;
  51285. this.faceId = -1;
  51286. this.subMeshId = 0;
  51287. this.pickedSprite = null;
  51288. }
  51289. // Methods
  51290. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  51291. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  51292. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  51293. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51294. return null;
  51295. }
  51296. var indices = this.pickedMesh.getIndices();
  51297. if (!indices) {
  51298. return null;
  51299. }
  51300. var result;
  51301. if (useVerticesNormals) {
  51302. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51303. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  51304. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  51305. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  51306. normal0 = normal0.scale(this.bu);
  51307. normal1 = normal1.scale(this.bv);
  51308. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  51309. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  51310. }
  51311. else {
  51312. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51313. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  51314. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  51315. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  51316. var p1p2 = vertex1.subtract(vertex2);
  51317. var p3p2 = vertex3.subtract(vertex2);
  51318. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  51319. }
  51320. if (useWorldCoordinates) {
  51321. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  51322. }
  51323. return BABYLON.Vector3.Normalize(result);
  51324. };
  51325. PickingInfo.prototype.getTextureCoordinates = function () {
  51326. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51327. return null;
  51328. }
  51329. var indices = this.pickedMesh.getIndices();
  51330. if (!indices) {
  51331. return null;
  51332. }
  51333. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51334. if (!uvs) {
  51335. return null;
  51336. }
  51337. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  51338. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  51339. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  51340. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  51341. uv1 = uv1.scale(this.bu);
  51342. uv2 = uv2.scale(this.bv);
  51343. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  51344. };
  51345. return PickingInfo;
  51346. }());
  51347. BABYLON.PickingInfo = PickingInfo;
  51348. })(BABYLON || (BABYLON = {}));
  51349. //# sourceMappingURL=babylon.pickingInfo.js.map
  51350. "use strict";
  51351. var BABYLON;
  51352. (function (BABYLON) {
  51353. var Ray = /** @class */ (function () {
  51354. function Ray(origin, direction, length) {
  51355. if (length === void 0) { length = Number.MAX_VALUE; }
  51356. this.origin = origin;
  51357. this.direction = direction;
  51358. this.length = length;
  51359. }
  51360. // Methods
  51361. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  51362. var d = 0.0;
  51363. var maxValue = Number.MAX_VALUE;
  51364. var inv;
  51365. var min;
  51366. var max;
  51367. var temp;
  51368. if (Math.abs(this.direction.x) < 0.0000001) {
  51369. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  51370. return false;
  51371. }
  51372. }
  51373. else {
  51374. inv = 1.0 / this.direction.x;
  51375. min = (minimum.x - this.origin.x) * inv;
  51376. max = (maximum.x - this.origin.x) * inv;
  51377. if (max === -Infinity) {
  51378. max = Infinity;
  51379. }
  51380. if (min > max) {
  51381. temp = min;
  51382. min = max;
  51383. max = temp;
  51384. }
  51385. d = Math.max(min, d);
  51386. maxValue = Math.min(max, maxValue);
  51387. if (d > maxValue) {
  51388. return false;
  51389. }
  51390. }
  51391. if (Math.abs(this.direction.y) < 0.0000001) {
  51392. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  51393. return false;
  51394. }
  51395. }
  51396. else {
  51397. inv = 1.0 / this.direction.y;
  51398. min = (minimum.y - this.origin.y) * inv;
  51399. max = (maximum.y - this.origin.y) * inv;
  51400. if (max === -Infinity) {
  51401. max = Infinity;
  51402. }
  51403. if (min > max) {
  51404. temp = min;
  51405. min = max;
  51406. max = temp;
  51407. }
  51408. d = Math.max(min, d);
  51409. maxValue = Math.min(max, maxValue);
  51410. if (d > maxValue) {
  51411. return false;
  51412. }
  51413. }
  51414. if (Math.abs(this.direction.z) < 0.0000001) {
  51415. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  51416. return false;
  51417. }
  51418. }
  51419. else {
  51420. inv = 1.0 / this.direction.z;
  51421. min = (minimum.z - this.origin.z) * inv;
  51422. max = (maximum.z - this.origin.z) * inv;
  51423. if (max === -Infinity) {
  51424. max = Infinity;
  51425. }
  51426. if (min > max) {
  51427. temp = min;
  51428. min = max;
  51429. max = temp;
  51430. }
  51431. d = Math.max(min, d);
  51432. maxValue = Math.min(max, maxValue);
  51433. if (d > maxValue) {
  51434. return false;
  51435. }
  51436. }
  51437. return true;
  51438. };
  51439. Ray.prototype.intersectsBox = function (box) {
  51440. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  51441. };
  51442. Ray.prototype.intersectsSphere = function (sphere) {
  51443. var x = sphere.center.x - this.origin.x;
  51444. var y = sphere.center.y - this.origin.y;
  51445. var z = sphere.center.z - this.origin.z;
  51446. var pyth = (x * x) + (y * y) + (z * z);
  51447. var rr = sphere.radius * sphere.radius;
  51448. if (pyth <= rr) {
  51449. return true;
  51450. }
  51451. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  51452. if (dot < 0.0) {
  51453. return false;
  51454. }
  51455. var temp = pyth - (dot * dot);
  51456. return temp <= rr;
  51457. };
  51458. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  51459. if (!this._edge1) {
  51460. this._edge1 = BABYLON.Vector3.Zero();
  51461. this._edge2 = BABYLON.Vector3.Zero();
  51462. this._pvec = BABYLON.Vector3.Zero();
  51463. this._tvec = BABYLON.Vector3.Zero();
  51464. this._qvec = BABYLON.Vector3.Zero();
  51465. }
  51466. vertex1.subtractToRef(vertex0, this._edge1);
  51467. vertex2.subtractToRef(vertex0, this._edge2);
  51468. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  51469. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  51470. if (det === 0) {
  51471. return null;
  51472. }
  51473. var invdet = 1 / det;
  51474. this.origin.subtractToRef(vertex0, this._tvec);
  51475. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  51476. if (bu < 0 || bu > 1.0) {
  51477. return null;
  51478. }
  51479. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  51480. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  51481. if (bv < 0 || bu + bv > 1.0) {
  51482. return null;
  51483. }
  51484. //check if the distance is longer than the predefined length.
  51485. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  51486. if (distance > this.length) {
  51487. return null;
  51488. }
  51489. return new BABYLON.IntersectionInfo(bu, bv, distance);
  51490. };
  51491. Ray.prototype.intersectsPlane = function (plane) {
  51492. var distance;
  51493. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  51494. if (Math.abs(result1) < 9.99999997475243E-07) {
  51495. return null;
  51496. }
  51497. else {
  51498. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  51499. distance = (-plane.d - result2) / result1;
  51500. if (distance < 0.0) {
  51501. if (distance < -9.99999997475243E-07) {
  51502. return null;
  51503. }
  51504. else {
  51505. return 0;
  51506. }
  51507. }
  51508. return distance;
  51509. }
  51510. };
  51511. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  51512. var tm = BABYLON.Tmp.Matrix[0];
  51513. mesh.getWorldMatrix().invertToRef(tm);
  51514. if (this._tmpRay) {
  51515. Ray.TransformToRef(this, tm, this._tmpRay);
  51516. }
  51517. else {
  51518. this._tmpRay = Ray.Transform(this, tm);
  51519. }
  51520. return mesh.intersects(this._tmpRay, fastCheck);
  51521. };
  51522. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  51523. if (results) {
  51524. results.length = 0;
  51525. }
  51526. else {
  51527. results = [];
  51528. }
  51529. for (var i = 0; i < meshes.length; i++) {
  51530. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  51531. if (pickInfo.hit) {
  51532. results.push(pickInfo);
  51533. }
  51534. }
  51535. results.sort(this._comparePickingInfo);
  51536. return results;
  51537. };
  51538. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  51539. if (pickingInfoA.distance < pickingInfoB.distance) {
  51540. return -1;
  51541. }
  51542. else if (pickingInfoA.distance > pickingInfoB.distance) {
  51543. return 1;
  51544. }
  51545. else {
  51546. return 0;
  51547. }
  51548. };
  51549. /**
  51550. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  51551. * @param sega the first point of the segment to test the intersection against
  51552. * @param segb the second point of the segment to test the intersection against
  51553. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  51554. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  51555. */
  51556. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  51557. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  51558. var u = segb.subtract(sega);
  51559. var v = rsegb.subtract(this.origin);
  51560. var w = sega.subtract(this.origin);
  51561. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  51562. var b = BABYLON.Vector3.Dot(u, v);
  51563. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  51564. var d = BABYLON.Vector3.Dot(u, w);
  51565. var e = BABYLON.Vector3.Dot(v, w);
  51566. var D = a * c - b * b; // always >= 0
  51567. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  51568. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  51569. // compute the line parameters of the two closest points
  51570. if (D < Ray.smallnum) {
  51571. sN = 0.0; // force using point P0 on segment S1
  51572. sD = 1.0; // to prevent possible division by 0.0 later
  51573. tN = e;
  51574. tD = c;
  51575. }
  51576. else {
  51577. sN = (b * e - c * d);
  51578. tN = (a * e - b * d);
  51579. if (sN < 0.0) {
  51580. sN = 0.0;
  51581. tN = e;
  51582. tD = c;
  51583. }
  51584. else if (sN > sD) {
  51585. sN = sD;
  51586. tN = e + b;
  51587. tD = c;
  51588. }
  51589. }
  51590. if (tN < 0.0) {
  51591. tN = 0.0;
  51592. // recompute sc for this edge
  51593. if (-d < 0.0) {
  51594. sN = 0.0;
  51595. }
  51596. else if (-d > a)
  51597. sN = sD;
  51598. else {
  51599. sN = -d;
  51600. sD = a;
  51601. }
  51602. }
  51603. else if (tN > tD) {
  51604. tN = tD;
  51605. // recompute sc for this edge
  51606. if ((-d + b) < 0.0) {
  51607. sN = 0;
  51608. }
  51609. else if ((-d + b) > a) {
  51610. sN = sD;
  51611. }
  51612. else {
  51613. sN = (-d + b);
  51614. sD = a;
  51615. }
  51616. }
  51617. // finally do the division to get sc and tc
  51618. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  51619. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  51620. // get the difference of the two closest points
  51621. var qtc = v.multiplyByFloats(tc, tc, tc);
  51622. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  51623. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  51624. if (isIntersected) {
  51625. return qtc.length();
  51626. }
  51627. return -1;
  51628. };
  51629. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  51630. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  51631. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  51632. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  51633. this.direction.normalize();
  51634. return this;
  51635. };
  51636. // Statics
  51637. Ray.Zero = function () {
  51638. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  51639. };
  51640. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  51641. var result = Ray.Zero();
  51642. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  51643. };
  51644. /**
  51645. * 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
  51646. * transformed to the given world matrix.
  51647. * @param origin The origin point
  51648. * @param end The end point
  51649. * @param world a matrix to transform the ray to. Default is the identity matrix.
  51650. */
  51651. Ray.CreateNewFromTo = function (origin, end, world) {
  51652. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  51653. var direction = end.subtract(origin);
  51654. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  51655. direction.normalize();
  51656. return Ray.Transform(new Ray(origin, direction, length), world);
  51657. };
  51658. Ray.Transform = function (ray, matrix) {
  51659. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  51660. Ray.TransformToRef(ray, matrix, result);
  51661. return result;
  51662. };
  51663. Ray.TransformToRef = function (ray, matrix, result) {
  51664. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  51665. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  51666. result.length = ray.length;
  51667. var dir = result.direction;
  51668. var len = dir.length();
  51669. if (!(len === 0 || len === 1)) {
  51670. var num = 1.0 / len;
  51671. dir.x *= num;
  51672. dir.y *= num;
  51673. dir.z *= num;
  51674. result.length *= len;
  51675. }
  51676. };
  51677. Ray.smallnum = 0.00000001;
  51678. Ray.rayl = 10e8;
  51679. return Ray;
  51680. }());
  51681. BABYLON.Ray = Ray;
  51682. })(BABYLON || (BABYLON = {}));
  51683. //# sourceMappingURL=babylon.ray.js.map
  51684. "use strict";
  51685. var BABYLON;
  51686. (function (BABYLON) {
  51687. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  51688. if (boxMin.x > sphereCenter.x + sphereRadius)
  51689. return false;
  51690. if (sphereCenter.x - sphereRadius > boxMax.x)
  51691. return false;
  51692. if (boxMin.y > sphereCenter.y + sphereRadius)
  51693. return false;
  51694. if (sphereCenter.y - sphereRadius > boxMax.y)
  51695. return false;
  51696. if (boxMin.z > sphereCenter.z + sphereRadius)
  51697. return false;
  51698. if (sphereCenter.z - sphereRadius > boxMax.z)
  51699. return false;
  51700. return true;
  51701. };
  51702. var getLowestRoot = (function () {
  51703. var result = { root: 0, found: false };
  51704. return function (a, b, c, maxR) {
  51705. result.root = 0;
  51706. result.found = false;
  51707. var determinant = b * b - 4.0 * a * c;
  51708. if (determinant < 0)
  51709. return result;
  51710. var sqrtD = Math.sqrt(determinant);
  51711. var r1 = (-b - sqrtD) / (2.0 * a);
  51712. var r2 = (-b + sqrtD) / (2.0 * a);
  51713. if (r1 > r2) {
  51714. var temp = r2;
  51715. r2 = r1;
  51716. r1 = temp;
  51717. }
  51718. if (r1 > 0 && r1 < maxR) {
  51719. result.root = r1;
  51720. result.found = true;
  51721. return result;
  51722. }
  51723. if (r2 > 0 && r2 < maxR) {
  51724. result.root = r2;
  51725. result.found = true;
  51726. return result;
  51727. }
  51728. return result;
  51729. };
  51730. })();
  51731. var Collider = /** @class */ (function () {
  51732. function Collider() {
  51733. this._collisionPoint = BABYLON.Vector3.Zero();
  51734. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  51735. this._tempVector = BABYLON.Vector3.Zero();
  51736. this._tempVector2 = BABYLON.Vector3.Zero();
  51737. this._tempVector3 = BABYLON.Vector3.Zero();
  51738. this._tempVector4 = BABYLON.Vector3.Zero();
  51739. this._edge = BABYLON.Vector3.Zero();
  51740. this._baseToVertex = BABYLON.Vector3.Zero();
  51741. this._destinationPoint = BABYLON.Vector3.Zero();
  51742. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  51743. this._displacementVector = BABYLON.Vector3.Zero();
  51744. this._radius = BABYLON.Vector3.One();
  51745. this._retry = 0;
  51746. this._basePointWorld = BABYLON.Vector3.Zero();
  51747. this._velocityWorld = BABYLON.Vector3.Zero();
  51748. this._normalizedVelocity = BABYLON.Vector3.Zero();
  51749. this._collisionMask = -1;
  51750. }
  51751. Object.defineProperty(Collider.prototype, "collisionMask", {
  51752. get: function () {
  51753. return this._collisionMask;
  51754. },
  51755. set: function (mask) {
  51756. this._collisionMask = !isNaN(mask) ? mask : -1;
  51757. },
  51758. enumerable: true,
  51759. configurable: true
  51760. });
  51761. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  51762. /**
  51763. * Gets the plane normal used to compute the sliding response (in local space)
  51764. */
  51765. get: function () {
  51766. return this._slidePlaneNormal;
  51767. },
  51768. enumerable: true,
  51769. configurable: true
  51770. });
  51771. // Methods
  51772. Collider.prototype._initialize = function (source, dir, e) {
  51773. this._velocity = dir;
  51774. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  51775. this._basePoint = source;
  51776. source.multiplyToRef(this._radius, this._basePointWorld);
  51777. dir.multiplyToRef(this._radius, this._velocityWorld);
  51778. this._velocityWorldLength = this._velocityWorld.length();
  51779. this._epsilon = e;
  51780. this.collisionFound = false;
  51781. };
  51782. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  51783. pa.subtractToRef(point, this._tempVector);
  51784. pb.subtractToRef(point, this._tempVector2);
  51785. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51786. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51787. if (d < 0)
  51788. return false;
  51789. pc.subtractToRef(point, this._tempVector3);
  51790. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51791. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51792. if (d < 0)
  51793. return false;
  51794. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51795. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51796. return d >= 0;
  51797. };
  51798. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51799. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51800. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51801. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51802. return false;
  51803. }
  51804. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51805. return false;
  51806. return true;
  51807. };
  51808. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51809. var t0;
  51810. var embeddedInPlane = false;
  51811. //defensive programming, actually not needed.
  51812. if (!trianglePlaneArray) {
  51813. trianglePlaneArray = [];
  51814. }
  51815. if (!trianglePlaneArray[faceIndex]) {
  51816. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51817. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51818. }
  51819. var trianglePlane = trianglePlaneArray[faceIndex];
  51820. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51821. return;
  51822. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51823. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51824. if (normalDotVelocity == 0) {
  51825. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51826. return;
  51827. embeddedInPlane = true;
  51828. t0 = 0;
  51829. }
  51830. else {
  51831. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51832. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51833. if (t0 > t1) {
  51834. var temp = t1;
  51835. t1 = t0;
  51836. t0 = temp;
  51837. }
  51838. if (t0 > 1.0 || t1 < 0.0)
  51839. return;
  51840. if (t0 < 0)
  51841. t0 = 0;
  51842. if (t0 > 1.0)
  51843. t0 = 1.0;
  51844. }
  51845. this._collisionPoint.copyFromFloats(0, 0, 0);
  51846. var found = false;
  51847. var t = 1.0;
  51848. if (!embeddedInPlane) {
  51849. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51850. this._velocity.scaleToRef(t0, this._tempVector);
  51851. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51852. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51853. found = true;
  51854. t = t0;
  51855. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51856. }
  51857. }
  51858. if (!found) {
  51859. var velocitySquaredLength = this._velocity.lengthSquared();
  51860. var a = velocitySquaredLength;
  51861. this._basePoint.subtractToRef(p1, this._tempVector);
  51862. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51863. var c = this._tempVector.lengthSquared() - 1.0;
  51864. var lowestRoot = getLowestRoot(a, b, c, t);
  51865. if (lowestRoot.found) {
  51866. t = lowestRoot.root;
  51867. found = true;
  51868. this._collisionPoint.copyFrom(p1);
  51869. }
  51870. this._basePoint.subtractToRef(p2, this._tempVector);
  51871. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51872. c = this._tempVector.lengthSquared() - 1.0;
  51873. lowestRoot = getLowestRoot(a, b, c, t);
  51874. if (lowestRoot.found) {
  51875. t = lowestRoot.root;
  51876. found = true;
  51877. this._collisionPoint.copyFrom(p2);
  51878. }
  51879. this._basePoint.subtractToRef(p3, this._tempVector);
  51880. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51881. c = this._tempVector.lengthSquared() - 1.0;
  51882. lowestRoot = getLowestRoot(a, b, c, t);
  51883. if (lowestRoot.found) {
  51884. t = lowestRoot.root;
  51885. found = true;
  51886. this._collisionPoint.copyFrom(p3);
  51887. }
  51888. p2.subtractToRef(p1, this._edge);
  51889. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51890. var edgeSquaredLength = this._edge.lengthSquared();
  51891. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51892. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51893. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51894. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51895. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51896. lowestRoot = getLowestRoot(a, b, c, t);
  51897. if (lowestRoot.found) {
  51898. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51899. if (f >= 0.0 && f <= 1.0) {
  51900. t = lowestRoot.root;
  51901. found = true;
  51902. this._edge.scaleInPlace(f);
  51903. p1.addToRef(this._edge, this._collisionPoint);
  51904. }
  51905. }
  51906. p3.subtractToRef(p2, this._edge);
  51907. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51908. edgeSquaredLength = this._edge.lengthSquared();
  51909. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51910. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51911. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51912. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51913. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51914. lowestRoot = getLowestRoot(a, b, c, t);
  51915. if (lowestRoot.found) {
  51916. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51917. if (f >= 0.0 && f <= 1.0) {
  51918. t = lowestRoot.root;
  51919. found = true;
  51920. this._edge.scaleInPlace(f);
  51921. p2.addToRef(this._edge, this._collisionPoint);
  51922. }
  51923. }
  51924. p1.subtractToRef(p3, this._edge);
  51925. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51926. edgeSquaredLength = this._edge.lengthSquared();
  51927. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51928. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51929. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51930. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51931. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51932. lowestRoot = getLowestRoot(a, b, c, t);
  51933. if (lowestRoot.found) {
  51934. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51935. if (f >= 0.0 && f <= 1.0) {
  51936. t = lowestRoot.root;
  51937. found = true;
  51938. this._edge.scaleInPlace(f);
  51939. p3.addToRef(this._edge, this._collisionPoint);
  51940. }
  51941. }
  51942. }
  51943. if (found) {
  51944. var distToCollision = t * this._velocity.length();
  51945. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51946. if (!this.intersectionPoint) {
  51947. this.intersectionPoint = this._collisionPoint.clone();
  51948. }
  51949. else {
  51950. this.intersectionPoint.copyFrom(this._collisionPoint);
  51951. }
  51952. this._nearestDistance = distToCollision;
  51953. this.collisionFound = true;
  51954. }
  51955. }
  51956. };
  51957. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51958. for (var i = indexStart; i < indexEnd; i += 3) {
  51959. var p1 = pts[indices[i] - decal];
  51960. var p2 = pts[indices[i + 1] - decal];
  51961. var p3 = pts[indices[i + 2] - decal];
  51962. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51963. }
  51964. };
  51965. Collider.prototype._getResponse = function (pos, vel) {
  51966. pos.addToRef(vel, this._destinationPoint);
  51967. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51968. this._basePoint.addToRef(vel, pos);
  51969. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51970. this._slidePlaneNormal.normalize();
  51971. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51972. pos.addInPlace(this._displacementVector);
  51973. this.intersectionPoint.addInPlace(this._displacementVector);
  51974. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51975. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51976. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51977. };
  51978. return Collider;
  51979. }());
  51980. BABYLON.Collider = Collider;
  51981. })(BABYLON || (BABYLON = {}));
  51982. //# sourceMappingURL=babylon.collider.js.map
  51983. "use strict";
  51984. var BABYLON;
  51985. (function (BABYLON) {
  51986. //WebWorker code will be inserted to this variable.
  51987. BABYLON.CollisionWorker = "";
  51988. var WorkerTaskType;
  51989. (function (WorkerTaskType) {
  51990. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51991. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51992. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51993. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51994. var WorkerReplyType;
  51995. (function (WorkerReplyType) {
  51996. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51997. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51998. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51999. var CollisionCoordinatorWorker = /** @class */ (function () {
  52000. function CollisionCoordinatorWorker() {
  52001. var _this = this;
  52002. this._scaledPosition = BABYLON.Vector3.Zero();
  52003. this._scaledVelocity = BABYLON.Vector3.Zero();
  52004. this.onMeshUpdated = function (transformNode) {
  52005. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  52006. };
  52007. this.onGeometryUpdated = function (geometry) {
  52008. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  52009. };
  52010. this._afterRender = function () {
  52011. if (!_this._init)
  52012. return;
  52013. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  52014. return;
  52015. }
  52016. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  52017. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  52018. if (_this._runningUpdated > 4) {
  52019. return;
  52020. }
  52021. ++_this._runningUpdated;
  52022. var payload = {
  52023. updatedMeshes: _this._addUpdateMeshesList,
  52024. updatedGeometries: _this._addUpdateGeometriesList,
  52025. removedGeometries: _this._toRemoveGeometryArray,
  52026. removedMeshes: _this._toRemoveMeshesArray
  52027. };
  52028. var message = {
  52029. payload: payload,
  52030. taskType: WorkerTaskType.UPDATE
  52031. };
  52032. var serializable = [];
  52033. for (var id in payload.updatedGeometries) {
  52034. if (payload.updatedGeometries.hasOwnProperty(id)) {
  52035. //prepare transferables
  52036. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  52037. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  52038. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  52039. }
  52040. }
  52041. _this._worker.postMessage(message, serializable);
  52042. _this._addUpdateMeshesList = {};
  52043. _this._addUpdateGeometriesList = {};
  52044. _this._toRemoveGeometryArray = [];
  52045. _this._toRemoveMeshesArray = [];
  52046. };
  52047. this._onMessageFromWorker = function (e) {
  52048. var returnData = e.data;
  52049. if (returnData.error != WorkerReplyType.SUCCESS) {
  52050. //TODO what errors can be returned from the worker?
  52051. BABYLON.Tools.Warn("error returned from worker!");
  52052. return;
  52053. }
  52054. switch (returnData.taskType) {
  52055. case WorkerTaskType.INIT:
  52056. _this._init = true;
  52057. //Update the worked with ALL of the scene's current state
  52058. _this._scene.meshes.forEach(function (mesh) {
  52059. _this.onMeshAdded(mesh);
  52060. });
  52061. _this._scene.getGeometries().forEach(function (geometry) {
  52062. _this.onGeometryAdded(geometry);
  52063. });
  52064. break;
  52065. case WorkerTaskType.UPDATE:
  52066. _this._runningUpdated--;
  52067. break;
  52068. case WorkerTaskType.COLLIDE:
  52069. var returnPayload = returnData.payload;
  52070. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  52071. return;
  52072. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  52073. if (callback) {
  52074. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  52075. if (mesh) {
  52076. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  52077. }
  52078. }
  52079. //cleanup
  52080. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  52081. break;
  52082. }
  52083. };
  52084. this._collisionsCallbackArray = [];
  52085. this._init = false;
  52086. this._runningUpdated = 0;
  52087. this._addUpdateMeshesList = {};
  52088. this._addUpdateGeometriesList = {};
  52089. this._toRemoveGeometryArray = [];
  52090. this._toRemoveMeshesArray = [];
  52091. }
  52092. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  52093. if (!this._init)
  52094. return;
  52095. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  52096. return;
  52097. position.divideToRef(collider._radius, this._scaledPosition);
  52098. displacement.divideToRef(collider._radius, this._scaledVelocity);
  52099. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  52100. var payload = {
  52101. collider: {
  52102. position: this._scaledPosition.asArray(),
  52103. velocity: this._scaledVelocity.asArray(),
  52104. radius: collider._radius.asArray()
  52105. },
  52106. collisionId: collisionIndex,
  52107. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  52108. maximumRetry: maximumRetry
  52109. };
  52110. var message = {
  52111. payload: payload,
  52112. taskType: WorkerTaskType.COLLIDE
  52113. };
  52114. this._worker.postMessage(message);
  52115. };
  52116. CollisionCoordinatorWorker.prototype.init = function (scene) {
  52117. this._scene = scene;
  52118. this._scene.registerAfterRender(this._afterRender);
  52119. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  52120. this._worker = new Worker(workerUrl);
  52121. this._worker.onmessage = this._onMessageFromWorker;
  52122. var message = {
  52123. payload: {},
  52124. taskType: WorkerTaskType.INIT
  52125. };
  52126. this._worker.postMessage(message);
  52127. };
  52128. CollisionCoordinatorWorker.prototype.destroy = function () {
  52129. this._scene.unregisterAfterRender(this._afterRender);
  52130. this._worker.terminate();
  52131. };
  52132. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  52133. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  52134. this.onMeshUpdated(mesh);
  52135. };
  52136. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  52137. this._toRemoveMeshesArray.push(mesh.uniqueId);
  52138. };
  52139. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  52140. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  52141. geometry.onGeometryUpdated = this.onGeometryUpdated;
  52142. this.onGeometryUpdated(geometry);
  52143. };
  52144. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  52145. this._toRemoveGeometryArray.push(geometry.id);
  52146. };
  52147. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  52148. var submeshes = [];
  52149. if (mesh.subMeshes) {
  52150. submeshes = mesh.subMeshes.map(function (sm, idx) {
  52151. var boundingInfo = sm.getBoundingInfo();
  52152. return {
  52153. position: idx,
  52154. verticesStart: sm.verticesStart,
  52155. verticesCount: sm.verticesCount,
  52156. indexStart: sm.indexStart,
  52157. indexCount: sm.indexCount,
  52158. hasMaterial: !!sm.getMaterial(),
  52159. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  52160. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  52161. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  52162. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  52163. };
  52164. });
  52165. }
  52166. var geometryId = null;
  52167. if (mesh instanceof BABYLON.Mesh) {
  52168. var geometry = mesh.geometry;
  52169. geometryId = geometry ? geometry.id : null;
  52170. }
  52171. else if (mesh instanceof BABYLON.InstancedMesh) {
  52172. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  52173. geometryId = geometry ? geometry.id : null;
  52174. }
  52175. var boundingInfo = mesh.getBoundingInfo();
  52176. return {
  52177. uniqueId: mesh.uniqueId,
  52178. id: mesh.id,
  52179. name: mesh.name,
  52180. geometryId: geometryId,
  52181. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  52182. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  52183. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  52184. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  52185. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  52186. subMeshes: submeshes,
  52187. checkCollisions: mesh.checkCollisions
  52188. };
  52189. };
  52190. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  52191. return {
  52192. id: geometry.id,
  52193. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  52194. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  52195. indices: new Uint32Array(geometry.getIndices() || []),
  52196. };
  52197. };
  52198. return CollisionCoordinatorWorker;
  52199. }());
  52200. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  52201. var CollisionCoordinatorLegacy = /** @class */ (function () {
  52202. function CollisionCoordinatorLegacy() {
  52203. this._scaledPosition = BABYLON.Vector3.Zero();
  52204. this._scaledVelocity = BABYLON.Vector3.Zero();
  52205. this._finalPosition = BABYLON.Vector3.Zero();
  52206. }
  52207. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  52208. position.divideToRef(collider._radius, this._scaledPosition);
  52209. displacement.divideToRef(collider._radius, this._scaledVelocity);
  52210. collider.collidedMesh = null;
  52211. collider._retry = 0;
  52212. collider._initialVelocity = this._scaledVelocity;
  52213. collider._initialPosition = this._scaledPosition;
  52214. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  52215. this._finalPosition.multiplyInPlace(collider._radius);
  52216. //run the callback
  52217. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  52218. };
  52219. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  52220. this._scene = scene;
  52221. };
  52222. CollisionCoordinatorLegacy.prototype.destroy = function () {
  52223. //Legacy need no destruction method.
  52224. };
  52225. //No update in legacy mode
  52226. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  52227. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  52228. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  52229. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  52230. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  52231. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  52232. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  52233. if (excludedMesh === void 0) { excludedMesh = null; }
  52234. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  52235. if (collider._retry >= maximumRetry) {
  52236. finalPosition.copyFrom(position);
  52237. return;
  52238. }
  52239. // Check if this is a mesh else camera or -1
  52240. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  52241. collider._initialize(position, velocity, closeDistance);
  52242. // Check all meshes
  52243. for (var index = 0; index < this._scene.meshes.length; index++) {
  52244. var mesh = this._scene.meshes[index];
  52245. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  52246. mesh._checkCollision(collider);
  52247. }
  52248. }
  52249. if (!collider.collisionFound) {
  52250. position.addToRef(velocity, finalPosition);
  52251. return;
  52252. }
  52253. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  52254. collider._getResponse(position, velocity);
  52255. }
  52256. if (velocity.length() <= closeDistance) {
  52257. finalPosition.copyFrom(position);
  52258. return;
  52259. }
  52260. collider._retry++;
  52261. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  52262. };
  52263. return CollisionCoordinatorLegacy;
  52264. }());
  52265. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  52266. })(BABYLON || (BABYLON = {}));
  52267. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  52268. "use strict";
  52269. var BABYLON;
  52270. (function (BABYLON) {
  52271. /**
  52272. * A particle represents one of the element emitted by a particle system.
  52273. * This is mainly define by its coordinates, direction, velocity and age.
  52274. */
  52275. var Particle = /** @class */ (function () {
  52276. /**
  52277. * Creates a new instance Particle
  52278. * @param particleSystem the particle system the particle belongs to
  52279. */
  52280. function Particle(
  52281. /**
  52282. * particleSystem the particle system the particle belongs to.
  52283. */
  52284. particleSystem) {
  52285. this.particleSystem = particleSystem;
  52286. /**
  52287. * The world position of the particle in the scene.
  52288. */
  52289. this.position = BABYLON.Vector3.Zero();
  52290. /**
  52291. * The world direction of the particle in the scene.
  52292. */
  52293. this.direction = BABYLON.Vector3.Zero();
  52294. /**
  52295. * The color of the particle.
  52296. */
  52297. this.color = new BABYLON.Color4(0, 0, 0, 0);
  52298. /**
  52299. * The color change of the particle per step.
  52300. */
  52301. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  52302. /**
  52303. * Defines how long will the life of the particle be.
  52304. */
  52305. this.lifeTime = 1.0;
  52306. /**
  52307. * The current age of the particle.
  52308. */
  52309. this.age = 0;
  52310. /**
  52311. * The current size of the particle.
  52312. */
  52313. this.size = 0;
  52314. /**
  52315. * The current angle of the particle.
  52316. */
  52317. this.angle = 0;
  52318. /**
  52319. * Defines how fast is the angle changing.
  52320. */
  52321. this.angularSpeed = 0;
  52322. /**
  52323. * Defines the cell index used by the particle to be rendered from a sprite.
  52324. */
  52325. this.cellIndex = 0;
  52326. this._currentFrameCounter = 0;
  52327. if (!this.particleSystem.isAnimationSheetEnabled) {
  52328. return;
  52329. }
  52330. this.updateCellInfoFromSystem();
  52331. }
  52332. Particle.prototype.updateCellInfoFromSystem = function () {
  52333. this.cellIndex = this.particleSystem.startSpriteCellID;
  52334. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  52335. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  52336. }
  52337. else {
  52338. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  52339. }
  52340. };
  52341. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  52342. // (ageOffset / scaledUpdateSpeed) / available cells
  52343. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  52344. this._currentFrameCounter += scaledUpdateSpeed;
  52345. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  52346. this._currentFrameCounter = 0;
  52347. this.cellIndex++;
  52348. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  52349. this.cellIndex = this.particleSystem.endSpriteCellID;
  52350. }
  52351. }
  52352. };
  52353. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  52354. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  52355. this.cellIndex++;
  52356. this._currentFrameCounter = 0;
  52357. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  52358. if (this.particleSystem.spriteCellLoop) {
  52359. this.cellIndex = this.particleSystem.startSpriteCellID;
  52360. }
  52361. else {
  52362. this.cellIndex = this.particleSystem.endSpriteCellID;
  52363. }
  52364. }
  52365. }
  52366. else {
  52367. this._currentFrameCounter++;
  52368. }
  52369. };
  52370. /**
  52371. * Copy the properties of particle to another one.
  52372. * @param other the particle to copy the information to.
  52373. */
  52374. Particle.prototype.copyTo = function (other) {
  52375. other.position.copyFrom(this.position);
  52376. other.direction.copyFrom(this.direction);
  52377. other.color.copyFrom(this.color);
  52378. other.colorStep.copyFrom(this.colorStep);
  52379. other.lifeTime = this.lifeTime;
  52380. other.age = this.age;
  52381. other.size = this.size;
  52382. other.angle = this.angle;
  52383. other.angularSpeed = this.angularSpeed;
  52384. other.particleSystem = this.particleSystem;
  52385. other.cellIndex = this.cellIndex;
  52386. };
  52387. return Particle;
  52388. }());
  52389. BABYLON.Particle = Particle;
  52390. })(BABYLON || (BABYLON = {}));
  52391. //# sourceMappingURL=babylon.particle.js.map
  52392. "use strict";
  52393. var BABYLON;
  52394. (function (BABYLON) {
  52395. /**
  52396. * This represents a particle system in Babylon.
  52397. * 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.
  52398. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  52399. * @example https://doc.babylonjs.com/babylon101/particles
  52400. */
  52401. var ParticleSystem = /** @class */ (function () {
  52402. /**
  52403. * Instantiates a particle system.
  52404. * 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.
  52405. * @param name The name of the particle system
  52406. * @param capacity The max number of particles alive at the same time
  52407. * @param scene The scene the particle system belongs to
  52408. * @param customEffect a custom effect used to change the way particles are rendered by default
  52409. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  52410. * @param epsilon Offset used to render the particles
  52411. */
  52412. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  52413. if (customEffect === void 0) { customEffect = null; }
  52414. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  52415. if (epsilon === void 0) { epsilon = 0.01; }
  52416. var _this = this;
  52417. /**
  52418. * List of animations used by the particle system.
  52419. */
  52420. this.animations = [];
  52421. /**
  52422. * The rendering group used by the Particle system to chose when to render.
  52423. */
  52424. this.renderingGroupId = 0;
  52425. /**
  52426. * The emitter represents the Mesh or position we are attaching the particle system to.
  52427. */
  52428. this.emitter = null;
  52429. /**
  52430. * The maximum number of particles to emit per frame
  52431. */
  52432. this.emitRate = 10;
  52433. /**
  52434. * If you want to launch only a few particles at once, that can be done, as well.
  52435. */
  52436. this.manualEmitCount = -1;
  52437. /**
  52438. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52439. */
  52440. this.updateSpeed = 0.01;
  52441. /**
  52442. * The amount of time the particle system is running (depends of the overall update speed).
  52443. */
  52444. this.targetStopDuration = 0;
  52445. /**
  52446. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  52447. */
  52448. this.disposeOnStop = false;
  52449. /**
  52450. * Minimum power of emitting particles.
  52451. */
  52452. this.minEmitPower = 1;
  52453. /**
  52454. * Maximum power of emitting particles.
  52455. */
  52456. this.maxEmitPower = 1;
  52457. /**
  52458. * Minimum life time of emitting particles.
  52459. */
  52460. this.minLifeTime = 1;
  52461. /**
  52462. * Maximum life time of emitting particles.
  52463. */
  52464. this.maxLifeTime = 1;
  52465. /**
  52466. * Minimum Size of emitting particles.
  52467. */
  52468. this.minSize = 1;
  52469. /**
  52470. * Maximum Size of emitting particles.
  52471. */
  52472. this.maxSize = 1;
  52473. /**
  52474. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  52475. */
  52476. this.minAngularSpeed = 0;
  52477. /**
  52478. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  52479. */
  52480. this.maxAngularSpeed = 0;
  52481. /**
  52482. * The layer mask we are rendering the particles through.
  52483. */
  52484. this.layerMask = 0x0FFFFFFF;
  52485. /**
  52486. * This can help using your own shader to render the particle system.
  52487. * The according effect will be created
  52488. */
  52489. this.customShader = null;
  52490. /**
  52491. * By default particle system starts as soon as they are created. This prevents the
  52492. * automatic start to happen and let you decide when to start emitting particles.
  52493. */
  52494. this.preventAutoStart = false;
  52495. /**
  52496. * Callback triggered when the particle animation is ending.
  52497. */
  52498. this.onAnimationEnd = null;
  52499. /**
  52500. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52501. */
  52502. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  52503. /**
  52504. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52505. * to override the particles.
  52506. */
  52507. this.forceDepthWrite = false;
  52508. /**
  52509. * You can use gravity if you want to give an orientation to your particles.
  52510. */
  52511. this.gravity = BABYLON.Vector3.Zero();
  52512. /**
  52513. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52514. */
  52515. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52516. /**
  52517. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52518. */
  52519. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52520. /**
  52521. * Color the particle will have at the end of its lifetime.
  52522. */
  52523. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  52524. /**
  52525. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  52526. */
  52527. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52528. /**
  52529. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  52530. */
  52531. this.spriteCellLoop = true;
  52532. /**
  52533. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  52534. */
  52535. this.spriteCellChangeSpeed = 0;
  52536. /**
  52537. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  52538. */
  52539. this.startSpriteCellID = 0;
  52540. /**
  52541. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  52542. */
  52543. this.endSpriteCellID = 0;
  52544. /**
  52545. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  52546. */
  52547. this.spriteCellWidth = 0;
  52548. /**
  52549. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  52550. */
  52551. this.spriteCellHeight = 0;
  52552. /**
  52553. * An event triggered when the system is disposed.
  52554. */
  52555. this.onDisposeObservable = new BABYLON.Observable();
  52556. this._particles = new Array();
  52557. this._stockParticles = new Array();
  52558. this._newPartsExcess = 0;
  52559. this._vertexBuffers = {};
  52560. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  52561. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  52562. this._scaledDirection = BABYLON.Vector3.Zero();
  52563. this._scaledGravity = BABYLON.Vector3.Zero();
  52564. this._currentRenderId = -1;
  52565. this._started = false;
  52566. this._stopped = false;
  52567. this._actualFrame = 0;
  52568. this._vertexBufferSize = 11;
  52569. // start of sub system methods
  52570. /**
  52571. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  52572. * Its lifetime will start back at 0.
  52573. */
  52574. this.recycleParticle = function (particle) {
  52575. var lastParticle = _this._particles.pop();
  52576. if (lastParticle !== particle) {
  52577. lastParticle.copyTo(particle);
  52578. }
  52579. _this._stockParticles.push(lastParticle);
  52580. };
  52581. this._createParticle = function () {
  52582. var particle;
  52583. if (_this._stockParticles.length !== 0) {
  52584. particle = _this._stockParticles.pop();
  52585. particle.age = 0;
  52586. particle.cellIndex = _this.startSpriteCellID;
  52587. }
  52588. else {
  52589. particle = new BABYLON.Particle(_this);
  52590. }
  52591. return particle;
  52592. };
  52593. this._emitFromParticle = function (particle) {
  52594. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  52595. return;
  52596. }
  52597. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  52598. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  52599. subSystem._rootParticleSystem = _this;
  52600. _this.activeSubSystems.push(subSystem);
  52601. subSystem.start();
  52602. };
  52603. this._appendParticleVertexes = null;
  52604. this.id = name;
  52605. this.name = name;
  52606. this._capacity = capacity;
  52607. this._epsilon = epsilon;
  52608. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  52609. if (isAnimationSheetEnabled) {
  52610. this._vertexBufferSize = 12;
  52611. }
  52612. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52613. this._customEffect = customEffect;
  52614. scene.particleSystems.push(this);
  52615. this._createIndexBuffer();
  52616. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  52617. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  52618. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  52619. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  52620. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  52621. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  52622. if (this._isAnimationSheetEnabled) {
  52623. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  52624. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  52625. }
  52626. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  52627. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  52628. this._vertexBuffers["options"] = options;
  52629. // Default emitter type
  52630. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  52631. this.updateFunction = function (particles) {
  52632. for (var index = 0; index < particles.length; index++) {
  52633. var particle = particles[index];
  52634. particle.age += _this._scaledUpdateSpeed;
  52635. if (particle.age >= particle.lifeTime) {
  52636. _this._emitFromParticle(particle);
  52637. _this.recycleParticle(particle);
  52638. index--;
  52639. continue;
  52640. }
  52641. else {
  52642. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  52643. particle.color.addInPlace(_this._scaledColorStep);
  52644. if (particle.color.a < 0)
  52645. particle.color.a = 0;
  52646. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  52647. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  52648. particle.position.addInPlace(_this._scaledDirection);
  52649. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  52650. particle.direction.addInPlace(_this._scaledGravity);
  52651. if (_this._isAnimationSheetEnabled) {
  52652. particle.updateCellIndex(_this._scaledUpdateSpeed);
  52653. }
  52654. }
  52655. }
  52656. };
  52657. }
  52658. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  52659. /**
  52660. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52661. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52662. */
  52663. get: function () {
  52664. if (this.particleEmitterType.direction1) {
  52665. return this.particleEmitterType.direction1;
  52666. }
  52667. return BABYLON.Vector3.Zero();
  52668. },
  52669. set: function (value) {
  52670. if (this.particleEmitterType.direction1) {
  52671. this.particleEmitterType.direction1 = value;
  52672. }
  52673. },
  52674. enumerable: true,
  52675. configurable: true
  52676. });
  52677. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  52678. /**
  52679. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52680. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52681. */
  52682. get: function () {
  52683. if (this.particleEmitterType.direction2) {
  52684. return this.particleEmitterType.direction2;
  52685. }
  52686. return BABYLON.Vector3.Zero();
  52687. },
  52688. set: function (value) {
  52689. if (this.particleEmitterType.direction2) {
  52690. this.particleEmitterType.direction2 = value;
  52691. }
  52692. },
  52693. enumerable: true,
  52694. configurable: true
  52695. });
  52696. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  52697. /**
  52698. * 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.
  52699. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52700. */
  52701. get: function () {
  52702. if (this.particleEmitterType.minEmitBox) {
  52703. return this.particleEmitterType.minEmitBox;
  52704. }
  52705. return BABYLON.Vector3.Zero();
  52706. },
  52707. set: function (value) {
  52708. if (this.particleEmitterType.minEmitBox) {
  52709. this.particleEmitterType.minEmitBox = value;
  52710. }
  52711. },
  52712. enumerable: true,
  52713. configurable: true
  52714. });
  52715. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  52716. /**
  52717. * 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.
  52718. * This only works when particleEmitterTyps is a BoxParticleEmitter
  52719. */
  52720. get: function () {
  52721. if (this.particleEmitterType.maxEmitBox) {
  52722. return this.particleEmitterType.maxEmitBox;
  52723. }
  52724. return BABYLON.Vector3.Zero();
  52725. },
  52726. set: function (value) {
  52727. if (this.particleEmitterType.maxEmitBox) {
  52728. this.particleEmitterType.maxEmitBox = value;
  52729. }
  52730. },
  52731. enumerable: true,
  52732. configurable: true
  52733. });
  52734. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  52735. /**
  52736. * Sets a callback that will be triggered when the system is disposed.
  52737. */
  52738. set: function (callback) {
  52739. if (this._onDisposeObserver) {
  52740. this.onDisposeObservable.remove(this._onDisposeObserver);
  52741. }
  52742. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  52743. },
  52744. enumerable: true,
  52745. configurable: true
  52746. });
  52747. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  52748. /**
  52749. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  52750. */
  52751. get: function () {
  52752. return this._isAnimationSheetEnabled;
  52753. },
  52754. enumerable: true,
  52755. configurable: true
  52756. });
  52757. Object.defineProperty(ParticleSystem.prototype, "particles", {
  52758. //end of Sub-emitter
  52759. /**
  52760. * Gets the current list of active particles
  52761. */
  52762. get: function () {
  52763. return this._particles;
  52764. },
  52765. enumerable: true,
  52766. configurable: true
  52767. });
  52768. /**
  52769. * Returns the string "ParticleSystem"
  52770. * @returns a string containing the class name
  52771. */
  52772. ParticleSystem.prototype.getClassName = function () {
  52773. return "ParticleSystem";
  52774. };
  52775. ParticleSystem.prototype._createIndexBuffer = function () {
  52776. var indices = [];
  52777. var index = 0;
  52778. for (var count = 0; count < this._capacity; count++) {
  52779. indices.push(index);
  52780. indices.push(index + 1);
  52781. indices.push(index + 2);
  52782. indices.push(index);
  52783. indices.push(index + 2);
  52784. indices.push(index + 3);
  52785. index += 4;
  52786. }
  52787. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52788. };
  52789. /**
  52790. * Gets the maximum number of particles active at the same time.
  52791. * @returns The max number of active particles.
  52792. */
  52793. ParticleSystem.prototype.getCapacity = function () {
  52794. return this._capacity;
  52795. };
  52796. /**
  52797. * Gets Wether there are still active particles in the system.
  52798. * @returns True if it is alive, otherwise false.
  52799. */
  52800. ParticleSystem.prototype.isAlive = function () {
  52801. return this._alive;
  52802. };
  52803. /**
  52804. * Gets Wether the system has been started.
  52805. * @returns True if it has been started, otherwise false.
  52806. */
  52807. ParticleSystem.prototype.isStarted = function () {
  52808. return this._started;
  52809. };
  52810. /**
  52811. * Starts the particle system and begins to emit.
  52812. */
  52813. ParticleSystem.prototype.start = function () {
  52814. this._started = true;
  52815. this._stopped = false;
  52816. this._actualFrame = 0;
  52817. if (this.subEmitters && this.subEmitters.length != 0) {
  52818. this.activeSubSystems = new Array();
  52819. }
  52820. };
  52821. /**
  52822. * Stops the particle system.
  52823. * @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.
  52824. */
  52825. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52826. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52827. this._stopped = true;
  52828. if (stopSubEmitters) {
  52829. this._stopSubEmitters();
  52830. }
  52831. };
  52832. // animation sheet
  52833. /**
  52834. * Remove all active particles
  52835. */
  52836. ParticleSystem.prototype.reset = function () {
  52837. this._stockParticles = [];
  52838. this._particles = [];
  52839. };
  52840. /**
  52841. * @ignore (for internal use only)
  52842. */
  52843. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52844. var offset = index * this._vertexBufferSize;
  52845. this._vertexData[offset] = particle.position.x;
  52846. this._vertexData[offset + 1] = particle.position.y;
  52847. this._vertexData[offset + 2] = particle.position.z;
  52848. this._vertexData[offset + 3] = particle.color.r;
  52849. this._vertexData[offset + 4] = particle.color.g;
  52850. this._vertexData[offset + 5] = particle.color.b;
  52851. this._vertexData[offset + 6] = particle.color.a;
  52852. this._vertexData[offset + 7] = particle.angle;
  52853. this._vertexData[offset + 8] = particle.size;
  52854. this._vertexData[offset + 9] = offsetX;
  52855. this._vertexData[offset + 10] = offsetY;
  52856. };
  52857. /**
  52858. * @ignore (for internal use only)
  52859. */
  52860. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52861. if (offsetX === 0)
  52862. offsetX = this._epsilon;
  52863. else if (offsetX === 1)
  52864. offsetX = 1 - this._epsilon;
  52865. if (offsetY === 0)
  52866. offsetY = this._epsilon;
  52867. else if (offsetY === 1)
  52868. offsetY = 1 - this._epsilon;
  52869. var offset = index * this._vertexBufferSize;
  52870. this._vertexData[offset] = particle.position.x;
  52871. this._vertexData[offset + 1] = particle.position.y;
  52872. this._vertexData[offset + 2] = particle.position.z;
  52873. this._vertexData[offset + 3] = particle.color.r;
  52874. this._vertexData[offset + 4] = particle.color.g;
  52875. this._vertexData[offset + 5] = particle.color.b;
  52876. this._vertexData[offset + 6] = particle.color.a;
  52877. this._vertexData[offset + 7] = particle.angle;
  52878. this._vertexData[offset + 8] = particle.size;
  52879. this._vertexData[offset + 9] = offsetX;
  52880. this._vertexData[offset + 10] = offsetY;
  52881. this._vertexData[offset + 11] = particle.cellIndex;
  52882. };
  52883. ParticleSystem.prototype._stopSubEmitters = function () {
  52884. if (!this.activeSubSystems) {
  52885. return;
  52886. }
  52887. this.activeSubSystems.forEach(function (subSystem) {
  52888. subSystem.stop(true);
  52889. });
  52890. this.activeSubSystems = new Array();
  52891. };
  52892. ParticleSystem.prototype._removeFromRoot = function () {
  52893. if (!this._rootParticleSystem) {
  52894. return;
  52895. }
  52896. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52897. if (index !== -1) {
  52898. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52899. }
  52900. };
  52901. // end of sub system methods
  52902. ParticleSystem.prototype._update = function (newParticles) {
  52903. // Update current
  52904. this._alive = this._particles.length > 0;
  52905. this.updateFunction(this._particles);
  52906. // Add new ones
  52907. var worldMatrix;
  52908. if (this.emitter.position) {
  52909. var emitterMesh = this.emitter;
  52910. worldMatrix = emitterMesh.getWorldMatrix();
  52911. }
  52912. else {
  52913. var emitterPosition = this.emitter;
  52914. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52915. }
  52916. var particle;
  52917. for (var index = 0; index < newParticles; index++) {
  52918. if (this._particles.length === this._capacity) {
  52919. break;
  52920. }
  52921. particle = this._createParticle();
  52922. this._particles.push(particle);
  52923. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52924. if (this.startPositionFunction) {
  52925. this.startPositionFunction(worldMatrix, particle.position, particle);
  52926. }
  52927. else {
  52928. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52929. }
  52930. if (this.startDirectionFunction) {
  52931. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52932. }
  52933. else {
  52934. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52935. }
  52936. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52937. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52938. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52939. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52940. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52941. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52942. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52943. }
  52944. };
  52945. ParticleSystem.prototype._getEffect = function () {
  52946. if (this._customEffect) {
  52947. return this._customEffect;
  52948. }
  52949. ;
  52950. var defines = [];
  52951. if (this._scene.clipPlane) {
  52952. defines.push("#define CLIPPLANE");
  52953. }
  52954. if (this._isAnimationSheetEnabled) {
  52955. defines.push("#define ANIMATESHEET");
  52956. }
  52957. // Effect
  52958. var join = defines.join("\n");
  52959. if (this._cachedDefines !== join) {
  52960. this._cachedDefines = join;
  52961. var attributesNamesOrOptions;
  52962. var effectCreationOption;
  52963. if (this._isAnimationSheetEnabled) {
  52964. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52965. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52966. }
  52967. else {
  52968. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52969. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52970. }
  52971. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52972. }
  52973. return this._effect;
  52974. };
  52975. /**
  52976. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52977. */
  52978. ParticleSystem.prototype.animate = function () {
  52979. if (!this._started)
  52980. return;
  52981. var effect = this._getEffect();
  52982. // Check
  52983. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52984. return;
  52985. if (this._currentRenderId === this._scene.getRenderId()) {
  52986. return;
  52987. }
  52988. this._currentRenderId = this._scene.getRenderId();
  52989. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52990. // determine the number of particles we need to create
  52991. var newParticles;
  52992. if (this.manualEmitCount > -1) {
  52993. newParticles = this.manualEmitCount;
  52994. this._newPartsExcess = 0;
  52995. this.manualEmitCount = 0;
  52996. }
  52997. else {
  52998. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52999. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  53000. }
  53001. if (this._newPartsExcess > 1.0) {
  53002. newParticles += this._newPartsExcess >> 0;
  53003. this._newPartsExcess -= this._newPartsExcess >> 0;
  53004. }
  53005. this._alive = false;
  53006. if (!this._stopped) {
  53007. this._actualFrame += this._scaledUpdateSpeed;
  53008. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  53009. this.stop();
  53010. }
  53011. else {
  53012. newParticles = 0;
  53013. }
  53014. this._update(newParticles);
  53015. // Stopped?
  53016. if (this._stopped) {
  53017. if (!this._alive) {
  53018. this._started = false;
  53019. if (this.onAnimationEnd) {
  53020. this.onAnimationEnd();
  53021. }
  53022. if (this.disposeOnStop) {
  53023. this._scene._toBeDisposed.push(this);
  53024. }
  53025. }
  53026. }
  53027. // Animation sheet
  53028. if (this._isAnimationSheetEnabled) {
  53029. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  53030. }
  53031. else {
  53032. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  53033. }
  53034. // Update VBO
  53035. var offset = 0;
  53036. for (var index = 0; index < this._particles.length; index++) {
  53037. var particle = this._particles[index];
  53038. this._appendParticleVertexes(offset, particle);
  53039. offset += 4;
  53040. }
  53041. if (this._vertexBuffer) {
  53042. this._vertexBuffer.update(this._vertexData);
  53043. }
  53044. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  53045. this.stop();
  53046. }
  53047. };
  53048. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  53049. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  53050. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  53051. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  53052. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  53053. };
  53054. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  53055. this._appendParticleVertex(offset++, particle, 0, 0);
  53056. this._appendParticleVertex(offset++, particle, 1, 0);
  53057. this._appendParticleVertex(offset++, particle, 1, 1);
  53058. this._appendParticleVertex(offset++, particle, 0, 1);
  53059. };
  53060. /**
  53061. * Rebuilds the particle system.
  53062. */
  53063. ParticleSystem.prototype.rebuild = function () {
  53064. this._createIndexBuffer();
  53065. if (this._vertexBuffer) {
  53066. this._vertexBuffer._rebuild();
  53067. }
  53068. };
  53069. /**
  53070. * Is this system ready to be used/rendered
  53071. * @return true if the system is ready
  53072. */
  53073. ParticleSystem.prototype.isReady = function () {
  53074. var effect = this._getEffect();
  53075. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53076. return false;
  53077. }
  53078. return true;
  53079. };
  53080. /**
  53081. * Renders the particle system in its current state.
  53082. * @returns the current number of particles
  53083. */
  53084. ParticleSystem.prototype.render = function () {
  53085. var effect = this._getEffect();
  53086. // Check
  53087. if (!this.isReady() || !this._particles.length) {
  53088. return 0;
  53089. }
  53090. var engine = this._scene.getEngine();
  53091. // Render
  53092. engine.enableEffect(effect);
  53093. engine.setState(false);
  53094. var viewMatrix = this._scene.getViewMatrix();
  53095. effect.setTexture("diffuseSampler", this.particleTexture);
  53096. effect.setMatrix("view", viewMatrix);
  53097. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53098. if (this._isAnimationSheetEnabled && this.particleTexture) {
  53099. var baseSize = this.particleTexture.getBaseSize();
  53100. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  53101. }
  53102. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  53103. if (this._scene.clipPlane) {
  53104. var clipPlane = this._scene.clipPlane;
  53105. var invView = viewMatrix.clone();
  53106. invView.invert();
  53107. effect.setMatrix("invView", invView);
  53108. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53109. }
  53110. // VBOs
  53111. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53112. // Draw order
  53113. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  53114. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53115. }
  53116. else {
  53117. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53118. }
  53119. if (this.forceDepthWrite) {
  53120. engine.setDepthWrite(true);
  53121. }
  53122. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  53123. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53124. return this._particles.length;
  53125. };
  53126. /**
  53127. * Disposes the particle system and free the associated resources
  53128. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53129. */
  53130. ParticleSystem.prototype.dispose = function (disposeTexture) {
  53131. if (disposeTexture === void 0) { disposeTexture = true; }
  53132. if (this._vertexBuffer) {
  53133. this._vertexBuffer.dispose();
  53134. this._vertexBuffer = null;
  53135. }
  53136. if (this._indexBuffer) {
  53137. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53138. this._indexBuffer = null;
  53139. }
  53140. if (disposeTexture && this.particleTexture) {
  53141. this.particleTexture.dispose();
  53142. this.particleTexture = null;
  53143. }
  53144. this._removeFromRoot();
  53145. // Remove from scene
  53146. var index = this._scene.particleSystems.indexOf(this);
  53147. if (index > -1) {
  53148. this._scene.particleSystems.splice(index, 1);
  53149. }
  53150. // Callback
  53151. this.onDisposeObservable.notifyObservers(this);
  53152. this.onDisposeObservable.clear();
  53153. };
  53154. /**
  53155. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  53156. * @param radius The radius of the sphere to emit from
  53157. * @returns the emitter
  53158. */
  53159. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  53160. if (radius === void 0) { radius = 1; }
  53161. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  53162. this.particleEmitterType = particleEmitter;
  53163. return particleEmitter;
  53164. };
  53165. /**
  53166. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  53167. * @param radius The radius of the sphere to emit from
  53168. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  53169. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  53170. * @returns the emitter
  53171. */
  53172. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  53173. if (radius === void 0) { radius = 1; }
  53174. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  53175. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  53176. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  53177. this.particleEmitterType = particleEmitter;
  53178. return particleEmitter;
  53179. };
  53180. /**
  53181. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  53182. * @param radius The radius of the cone to emit from
  53183. * @param angle The base angle of the cone
  53184. * @returns the emitter
  53185. */
  53186. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  53187. if (radius === void 0) { radius = 1; }
  53188. if (angle === void 0) { angle = Math.PI / 4; }
  53189. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  53190. this.particleEmitterType = particleEmitter;
  53191. return particleEmitter;
  53192. };
  53193. // 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.
  53194. /**
  53195. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  53196. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  53197. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  53198. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  53199. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  53200. * @returns the emitter
  53201. */
  53202. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  53203. var particleEmitter = new BABYLON.BoxParticleEmitter();
  53204. this.particleEmitterType = particleEmitter;
  53205. this.direction1 = direction1;
  53206. this.direction2 = direction2;
  53207. this.minEmitBox = minEmitBox;
  53208. this.maxEmitBox = maxEmitBox;
  53209. return particleEmitter;
  53210. };
  53211. // Clone
  53212. /**
  53213. * Clones the particle system.
  53214. * @param name The name of the cloned object
  53215. * @param newEmitter The new emitter to use
  53216. * @returns the cloned particle system
  53217. */
  53218. ParticleSystem.prototype.clone = function (name, newEmitter) {
  53219. var custom = null;
  53220. var program = null;
  53221. if (this.customShader != null) {
  53222. program = this.customShader;
  53223. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  53224. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  53225. }
  53226. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  53227. result.customShader = program;
  53228. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  53229. if (newEmitter === undefined) {
  53230. newEmitter = this.emitter;
  53231. }
  53232. result.emitter = newEmitter;
  53233. if (this.particleTexture) {
  53234. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53235. }
  53236. if (!this.preventAutoStart) {
  53237. result.start();
  53238. }
  53239. return result;
  53240. };
  53241. /**
  53242. * Serializes the particle system to a JSON object.
  53243. * @returns the JSON object
  53244. */
  53245. ParticleSystem.prototype.serialize = function () {
  53246. var serializationObject = {};
  53247. serializationObject.name = this.name;
  53248. serializationObject.id = this.id;
  53249. // Emitter
  53250. if (this.emitter.position) {
  53251. var emitterMesh = this.emitter;
  53252. serializationObject.emitterId = emitterMesh.id;
  53253. }
  53254. else {
  53255. var emitterPosition = this.emitter;
  53256. serializationObject.emitter = emitterPosition.asArray();
  53257. }
  53258. serializationObject.capacity = this.getCapacity();
  53259. if (this.particleTexture) {
  53260. serializationObject.textureName = this.particleTexture.name;
  53261. }
  53262. // Animations
  53263. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53264. // Particle system
  53265. serializationObject.minAngularSpeed = this.minAngularSpeed;
  53266. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  53267. serializationObject.minSize = this.minSize;
  53268. serializationObject.maxSize = this.maxSize;
  53269. serializationObject.minEmitPower = this.minEmitPower;
  53270. serializationObject.maxEmitPower = this.maxEmitPower;
  53271. serializationObject.minLifeTime = this.minLifeTime;
  53272. serializationObject.maxLifeTime = this.maxLifeTime;
  53273. serializationObject.emitRate = this.emitRate;
  53274. serializationObject.minEmitBox = this.minEmitBox.asArray();
  53275. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  53276. serializationObject.gravity = this.gravity.asArray();
  53277. serializationObject.direction1 = this.direction1.asArray();
  53278. serializationObject.direction2 = this.direction2.asArray();
  53279. serializationObject.color1 = this.color1.asArray();
  53280. serializationObject.color2 = this.color2.asArray();
  53281. serializationObject.colorDead = this.colorDead.asArray();
  53282. serializationObject.updateSpeed = this.updateSpeed;
  53283. serializationObject.targetStopDuration = this.targetStopDuration;
  53284. serializationObject.textureMask = this.textureMask.asArray();
  53285. serializationObject.blendMode = this.blendMode;
  53286. serializationObject.customShader = this.customShader;
  53287. serializationObject.preventAutoStart = this.preventAutoStart;
  53288. serializationObject.startSpriteCellID = this.startSpriteCellID;
  53289. serializationObject.endSpriteCellID = this.endSpriteCellID;
  53290. serializationObject.spriteCellLoop = this.spriteCellLoop;
  53291. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  53292. serializationObject.spriteCellWidth = this.spriteCellWidth;
  53293. serializationObject.spriteCellHeight = this.spriteCellHeight;
  53294. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  53295. // Emitter
  53296. if (this.particleEmitterType) {
  53297. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53298. }
  53299. return serializationObject;
  53300. };
  53301. /**
  53302. * Parses a JSON object to create a particle system.
  53303. * @param parsedParticleSystem The JSON object to parse
  53304. * @param scene The scene to create the particle system in
  53305. * @param rootUrl The root url to use to load external dependencies like texture
  53306. * @returns the Parsed particle system
  53307. */
  53308. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53309. var name = parsedParticleSystem.name;
  53310. var custom = null;
  53311. var program = null;
  53312. if (parsedParticleSystem.customShader) {
  53313. program = parsedParticleSystem.customShader;
  53314. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  53315. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  53316. }
  53317. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  53318. particleSystem.customShader = program;
  53319. if (parsedParticleSystem.id) {
  53320. particleSystem.id = parsedParticleSystem.id;
  53321. }
  53322. // Auto start
  53323. if (parsedParticleSystem.preventAutoStart) {
  53324. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  53325. }
  53326. // Texture
  53327. if (parsedParticleSystem.textureName) {
  53328. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53329. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53330. }
  53331. // Emitter
  53332. if (parsedParticleSystem.emitterId) {
  53333. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53334. }
  53335. else {
  53336. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53337. }
  53338. // Animations
  53339. if (parsedParticleSystem.animations) {
  53340. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53341. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53342. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53343. }
  53344. }
  53345. if (parsedParticleSystem.autoAnimate) {
  53346. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  53347. }
  53348. // Particle system
  53349. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  53350. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  53351. particleSystem.minSize = parsedParticleSystem.minSize;
  53352. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53353. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53354. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53355. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53356. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53357. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53358. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  53359. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  53360. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53361. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  53362. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  53363. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53364. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53365. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53366. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53367. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53368. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  53369. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53370. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  53371. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  53372. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  53373. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  53374. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  53375. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  53376. if (!particleSystem.preventAutoStart) {
  53377. particleSystem.start();
  53378. }
  53379. return particleSystem;
  53380. };
  53381. /**
  53382. * Source color is added to the destination color without alpha affecting the result.
  53383. */
  53384. ParticleSystem.BLENDMODE_ONEONE = 0;
  53385. /**
  53386. * Blend current color and particle color using particle’s alpha.
  53387. */
  53388. ParticleSystem.BLENDMODE_STANDARD = 1;
  53389. return ParticleSystem;
  53390. }());
  53391. BABYLON.ParticleSystem = ParticleSystem;
  53392. })(BABYLON || (BABYLON = {}));
  53393. //# sourceMappingURL=babylon.particleSystem.js.map
  53394. "use strict";
  53395. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  53396. "use strict";
  53397. var BABYLON;
  53398. (function (BABYLON) {
  53399. /**
  53400. * Particle emitter emitting particles from the inside of a box.
  53401. * It emits the particles randomly between 2 given directions.
  53402. */
  53403. var BoxParticleEmitter = /** @class */ (function () {
  53404. /**
  53405. * Creates a new instance BoxParticleEmitter
  53406. */
  53407. function BoxParticleEmitter() {
  53408. /**
  53409. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53410. */
  53411. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  53412. /**
  53413. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53414. */
  53415. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  53416. /**
  53417. * 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.
  53418. */
  53419. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  53420. /**
  53421. * 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.
  53422. */
  53423. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  53424. }
  53425. /**
  53426. * Called by the particle System when the direction is computed for the created particle.
  53427. * @param emitPower is the power of the particle (speed)
  53428. * @param worldMatrix is the world matrix of the particle system
  53429. * @param directionToUpdate is the direction vector to update with the result
  53430. * @param particle is the particle we are computed the direction for
  53431. */
  53432. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53433. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53434. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53435. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53436. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53437. };
  53438. /**
  53439. * Called by the particle System when the position is computed for the created particle.
  53440. * @param worldMatrix is the world matrix of the particle system
  53441. * @param positionToUpdate is the position vector to update with the result
  53442. * @param particle is the particle we are computed the position for
  53443. */
  53444. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53445. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  53446. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  53447. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  53448. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53449. };
  53450. /**
  53451. * Clones the current emitter and returns a copy of it
  53452. * @returns the new emitter
  53453. */
  53454. BoxParticleEmitter.prototype.clone = function () {
  53455. var newOne = new BoxParticleEmitter();
  53456. BABYLON.Tools.DeepCopy(this, newOne);
  53457. return newOne;
  53458. };
  53459. /**
  53460. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53461. * @param effect defines the update shader
  53462. */
  53463. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  53464. effect.setVector3("direction1", this.direction1);
  53465. effect.setVector3("direction2", this.direction2);
  53466. effect.setVector3("minEmitBox", this.minEmitBox);
  53467. effect.setVector3("maxEmitBox", this.maxEmitBox);
  53468. };
  53469. /**
  53470. * Returns a string to use to update the GPU particles update shader
  53471. * @returns a string containng the defines string
  53472. */
  53473. BoxParticleEmitter.prototype.getEffectDefines = function () {
  53474. return "#define BOXEMITTER";
  53475. };
  53476. /**
  53477. * Returns the string "BoxEmitter"
  53478. * @returns a string containing the class name
  53479. */
  53480. BoxParticleEmitter.prototype.getClassName = function () {
  53481. return "BoxEmitter";
  53482. };
  53483. /**
  53484. * Serializes the particle system to a JSON object.
  53485. * @returns the JSON object
  53486. */
  53487. BoxParticleEmitter.prototype.serialize = function () {
  53488. var serializationObject = {};
  53489. serializationObject.type = this.getClassName();
  53490. serializationObject.direction1 = this.direction1.asArray();
  53491. ;
  53492. serializationObject.direction2 = this.direction2.asArray();
  53493. ;
  53494. serializationObject.minEmitBox = this.minEmitBox.asArray();
  53495. ;
  53496. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  53497. ;
  53498. return serializationObject;
  53499. };
  53500. /**
  53501. * Parse properties from a JSON object
  53502. * @param serializationObject defines the JSON object
  53503. */
  53504. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  53505. this.direction1.copyFrom(serializationObject.direction1);
  53506. this.direction2.copyFrom(serializationObject.direction2);
  53507. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  53508. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  53509. };
  53510. return BoxParticleEmitter;
  53511. }());
  53512. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  53513. })(BABYLON || (BABYLON = {}));
  53514. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  53515. "use strict";
  53516. var BABYLON;
  53517. (function (BABYLON) {
  53518. /**
  53519. * Particle emitter emitting particles from the inside of a cone.
  53520. * It emits the particles alongside the cone volume from the base to the particle.
  53521. * The emission direction might be randomized.
  53522. */
  53523. var ConeParticleEmitter = /** @class */ (function () {
  53524. /**
  53525. * Creates a new instance ConeParticleEmitter
  53526. * @param radius the radius of the emission cone (1 by default)
  53527. * @param angles the cone base angle (PI by default)
  53528. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  53529. */
  53530. function ConeParticleEmitter(radius,
  53531. /**
  53532. * The radius of the emission cone.
  53533. */
  53534. angle,
  53535. /**
  53536. * The cone base angle.
  53537. */
  53538. directionRandomizer) {
  53539. if (radius === void 0) { radius = 1; }
  53540. if (angle === void 0) { angle = Math.PI; }
  53541. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  53542. this.angle = angle;
  53543. this.directionRandomizer = directionRandomizer;
  53544. this.radius = radius;
  53545. }
  53546. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  53547. /**
  53548. * Gets the radius of the emission cone.
  53549. */
  53550. get: function () {
  53551. return this._radius;
  53552. },
  53553. /**
  53554. * Sets the radius of the emission cone.
  53555. */
  53556. set: function (value) {
  53557. this._radius = value;
  53558. if (this.angle !== 0) {
  53559. this._height = value / Math.tan(this.angle / 2);
  53560. }
  53561. else {
  53562. this._height = 1;
  53563. }
  53564. },
  53565. enumerable: true,
  53566. configurable: true
  53567. });
  53568. /**
  53569. * Called by the particle System when the direction is computed for the created particle.
  53570. * @param emitPower is the power of the particle (speed)
  53571. * @param worldMatrix is the world matrix of the particle system
  53572. * @param directionToUpdate is the direction vector to update with the result
  53573. * @param particle is the particle we are computed the direction for
  53574. */
  53575. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53576. if (this.angle === 0) {
  53577. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  53578. }
  53579. else {
  53580. // measure the direction Vector from the emitter to the particle.
  53581. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  53582. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53583. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53584. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53585. direction.x += randX;
  53586. direction.y += randY;
  53587. direction.z += randZ;
  53588. direction.normalize();
  53589. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  53590. }
  53591. };
  53592. /**
  53593. * Called by the particle System when the position is computed for the created particle.
  53594. * @param worldMatrix is the world matrix of the particle system
  53595. * @param positionToUpdate is the position vector to update with the result
  53596. * @param particle is the particle we are computed the position for
  53597. */
  53598. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53599. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  53600. var h = BABYLON.Scalar.RandomRange(0, 1);
  53601. // Better distribution in a cone at normal angles.
  53602. h = 1 - h * h;
  53603. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  53604. radius = radius * h;
  53605. var randX = radius * Math.sin(s);
  53606. var randZ = radius * Math.cos(s);
  53607. var randY = h * this._height;
  53608. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53609. };
  53610. /**
  53611. * Clones the current emitter and returns a copy of it
  53612. * @returns the new emitter
  53613. */
  53614. ConeParticleEmitter.prototype.clone = function () {
  53615. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  53616. BABYLON.Tools.DeepCopy(this, newOne);
  53617. return newOne;
  53618. };
  53619. /**
  53620. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53621. * @param effect defines the update shader
  53622. */
  53623. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  53624. effect.setFloat("radius", this.radius);
  53625. effect.setFloat("angle", this.angle);
  53626. effect.setFloat("height", this._height);
  53627. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53628. };
  53629. /**
  53630. * Returns a string to use to update the GPU particles update shader
  53631. * @returns a string containng the defines string
  53632. */
  53633. ConeParticleEmitter.prototype.getEffectDefines = function () {
  53634. return "#define CONEEMITTER";
  53635. };
  53636. /**
  53637. * Returns the string "BoxEmitter"
  53638. * @returns a string containing the class name
  53639. */
  53640. ConeParticleEmitter.prototype.getClassName = function () {
  53641. return "ConeEmitter";
  53642. };
  53643. /**
  53644. * Serializes the particle system to a JSON object.
  53645. * @returns the JSON object
  53646. */
  53647. ConeParticleEmitter.prototype.serialize = function () {
  53648. var serializationObject = {};
  53649. serializationObject.type = this.getClassName();
  53650. serializationObject.radius = this.radius;
  53651. serializationObject.angle = this.angle;
  53652. serializationObject.directionRandomizer = this.directionRandomizer;
  53653. return serializationObject;
  53654. };
  53655. /**
  53656. * Parse properties from a JSON object
  53657. * @param serializationObject defines the JSON object
  53658. */
  53659. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  53660. this.radius = serializationObject.radius;
  53661. this.angle = serializationObject.angle;
  53662. this.directionRandomizer = serializationObject.directionRandomizer;
  53663. };
  53664. return ConeParticleEmitter;
  53665. }());
  53666. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  53667. })(BABYLON || (BABYLON = {}));
  53668. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  53669. "use strict";
  53670. var BABYLON;
  53671. (function (BABYLON) {
  53672. /**
  53673. * Particle emitter emitting particles from the inside of a sphere.
  53674. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  53675. */
  53676. var SphereParticleEmitter = /** @class */ (function () {
  53677. /**
  53678. * Creates a new instance SphereParticleEmitter
  53679. * @param radius the radius of the emission sphere (1 by default)
  53680. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  53681. */
  53682. function SphereParticleEmitter(
  53683. /**
  53684. * The radius of the emission sphere.
  53685. */
  53686. radius,
  53687. /**
  53688. * How much to randomize the particle direction [0-1].
  53689. */
  53690. directionRandomizer) {
  53691. if (radius === void 0) { radius = 1; }
  53692. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  53693. this.radius = radius;
  53694. this.directionRandomizer = directionRandomizer;
  53695. }
  53696. /**
  53697. * Called by the particle System when the direction is computed for the created particle.
  53698. * @param emitPower is the power of the particle (speed)
  53699. * @param worldMatrix is the world matrix of the particle system
  53700. * @param directionToUpdate is the direction vector to update with the result
  53701. * @param particle is the particle we are computed the direction for
  53702. */
  53703. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53704. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  53705. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53706. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53707. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  53708. direction.x += randX;
  53709. direction.y += randY;
  53710. direction.z += randZ;
  53711. direction.normalize();
  53712. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  53713. };
  53714. /**
  53715. * Called by the particle System when the position is computed for the created particle.
  53716. * @param worldMatrix is the world matrix of the particle system
  53717. * @param positionToUpdate is the position vector to update with the result
  53718. * @param particle is the particle we are computed the position for
  53719. */
  53720. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  53721. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  53722. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  53723. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  53724. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  53725. var randY = randRadius * Math.cos(theta);
  53726. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  53727. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  53728. };
  53729. /**
  53730. * Clones the current emitter and returns a copy of it
  53731. * @returns the new emitter
  53732. */
  53733. SphereParticleEmitter.prototype.clone = function () {
  53734. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  53735. BABYLON.Tools.DeepCopy(this, newOne);
  53736. return newOne;
  53737. };
  53738. /**
  53739. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53740. * @param effect defines the update shader
  53741. */
  53742. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  53743. effect.setFloat("radius", this.radius);
  53744. effect.setFloat("directionRandomizer", this.directionRandomizer);
  53745. };
  53746. /**
  53747. * Returns a string to use to update the GPU particles update shader
  53748. * @returns a string containng the defines string
  53749. */
  53750. SphereParticleEmitter.prototype.getEffectDefines = function () {
  53751. return "#define SPHEREEMITTER";
  53752. };
  53753. /**
  53754. * Returns the string "SphereParticleEmitter"
  53755. * @returns a string containing the class name
  53756. */
  53757. SphereParticleEmitter.prototype.getClassName = function () {
  53758. return "SphereParticleEmitter";
  53759. };
  53760. /**
  53761. * Serializes the particle system to a JSON object.
  53762. * @returns the JSON object
  53763. */
  53764. SphereParticleEmitter.prototype.serialize = function () {
  53765. var serializationObject = {};
  53766. serializationObject.type = this.getClassName();
  53767. serializationObject.radius = this.radius;
  53768. serializationObject.directionRandomizer = this.directionRandomizer;
  53769. return serializationObject;
  53770. };
  53771. /**
  53772. * Parse properties from a JSON object
  53773. * @param serializationObject defines the JSON object
  53774. */
  53775. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  53776. this.radius = serializationObject.radius;
  53777. this.directionRandomizer = serializationObject.directionRandomizer;
  53778. };
  53779. return SphereParticleEmitter;
  53780. }());
  53781. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  53782. /**
  53783. * Particle emitter emitting particles from the inside of a sphere.
  53784. * It emits the particles randomly between two vectors.
  53785. */
  53786. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53787. __extends(SphereDirectedParticleEmitter, _super);
  53788. /**
  53789. * Creates a new instance SphereDirectedParticleEmitter
  53790. * @param radius the radius of the emission sphere (1 by default)
  53791. * @param direction1 the min limit of the emission direction (up vector by default)
  53792. * @param direction2 the max limit of the emission direction (up vector by default)
  53793. */
  53794. function SphereDirectedParticleEmitter(radius,
  53795. /**
  53796. * The min limit of the emission direction.
  53797. */
  53798. direction1,
  53799. /**
  53800. * The max limit of the emission direction.
  53801. */
  53802. direction2) {
  53803. if (radius === void 0) { radius = 1; }
  53804. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53805. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53806. var _this = _super.call(this, radius) || this;
  53807. _this.direction1 = direction1;
  53808. _this.direction2 = direction2;
  53809. return _this;
  53810. }
  53811. /**
  53812. * Called by the particle System when the direction is computed for the created particle.
  53813. * @param emitPower is the power of the particle (speed)
  53814. * @param worldMatrix is the world matrix of the particle system
  53815. * @param directionToUpdate is the direction vector to update with the result
  53816. * @param particle is the particle we are computed the direction for
  53817. */
  53818. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53819. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53820. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53821. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53822. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53823. };
  53824. /**
  53825. * Clones the current emitter and returns a copy of it
  53826. * @returns the new emitter
  53827. */
  53828. SphereDirectedParticleEmitter.prototype.clone = function () {
  53829. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53830. BABYLON.Tools.DeepCopy(this, newOne);
  53831. return newOne;
  53832. };
  53833. /**
  53834. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53835. * @param effect defines the update shader
  53836. */
  53837. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53838. effect.setFloat("radius", this.radius);
  53839. effect.setVector3("direction1", this.direction1);
  53840. effect.setVector3("direction2", this.direction2);
  53841. };
  53842. /**
  53843. * Returns a string to use to update the GPU particles update shader
  53844. * @returns a string containng the defines string
  53845. */
  53846. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53847. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53848. };
  53849. /**
  53850. * Returns the string "SphereDirectedParticleEmitter"
  53851. * @returns a string containing the class name
  53852. */
  53853. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53854. return "SphereDirectedParticleEmitter";
  53855. };
  53856. /**
  53857. * Serializes the particle system to a JSON object.
  53858. * @returns the JSON object
  53859. */
  53860. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53861. var serializationObject = _super.prototype.serialize.call(this);
  53862. ;
  53863. serializationObject.direction1 = this.direction1.asArray();
  53864. ;
  53865. serializationObject.direction2 = this.direction2.asArray();
  53866. ;
  53867. return serializationObject;
  53868. };
  53869. /**
  53870. * Parse properties from a JSON object
  53871. * @param serializationObject defines the JSON object
  53872. */
  53873. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53874. _super.prototype.parse.call(this, serializationObject);
  53875. this.direction1.copyFrom(serializationObject.direction1);
  53876. this.direction2.copyFrom(serializationObject.direction2);
  53877. };
  53878. return SphereDirectedParticleEmitter;
  53879. }(SphereParticleEmitter));
  53880. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53881. })(BABYLON || (BABYLON = {}));
  53882. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53883. "use strict";
  53884. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53885. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53886. s = arguments[i];
  53887. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53888. t[p] = s[p];
  53889. }
  53890. return t;
  53891. };
  53892. var BABYLON;
  53893. (function (BABYLON) {
  53894. /**
  53895. * This represents a GPU particle system in Babylon
  53896. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53897. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53898. */
  53899. var GPUParticleSystem = /** @class */ (function () {
  53900. /**
  53901. * Instantiates a GPU particle system.
  53902. * 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.
  53903. * @param name The name of the particle system
  53904. * @param capacity The max number of particles alive at the same time
  53905. * @param scene The scene the particle system belongs to
  53906. */
  53907. function GPUParticleSystem(name, options, scene) {
  53908. /**
  53909. * The emitter represents the Mesh or position we are attaching the particle system to.
  53910. */
  53911. this.emitter = null;
  53912. /**
  53913. * The rendering group used by the Particle system to chose when to render.
  53914. */
  53915. this.renderingGroupId = 0;
  53916. /**
  53917. * The layer mask we are rendering the particles through.
  53918. */
  53919. this.layerMask = 0x0FFFFFFF;
  53920. this._targetIndex = 0;
  53921. this._currentRenderId = -1;
  53922. this._started = false;
  53923. this._stopped = false;
  53924. this._timeDelta = 0;
  53925. this._attributesStrideSize = 14;
  53926. this._actualFrame = 0;
  53927. /**
  53928. * List of animations used by the particle system.
  53929. */
  53930. this.animations = [];
  53931. /**
  53932. * An event triggered when the system is disposed.
  53933. */
  53934. this.onDisposeObservable = new BABYLON.Observable();
  53935. /**
  53936. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53937. */
  53938. this.updateSpeed = 0.01;
  53939. /**
  53940. * The amount of time the particle system is running (depends of the overall update speed).
  53941. */
  53942. this.targetStopDuration = 0;
  53943. /**
  53944. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53945. */
  53946. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53947. /**
  53948. * Minimum life time of emitting particles.
  53949. */
  53950. this.minLifeTime = 1;
  53951. /**
  53952. * Maximum life time of emitting particles.
  53953. */
  53954. this.maxLifeTime = 1;
  53955. /**
  53956. * Minimum Size of emitting particles.
  53957. */
  53958. this.minSize = 1;
  53959. /**
  53960. * Maximum Size of emitting particles.
  53961. */
  53962. this.maxSize = 1;
  53963. /**
  53964. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53965. */
  53966. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53967. /**
  53968. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53969. */
  53970. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53971. /**
  53972. * Color the particle will have at the end of its lifetime.
  53973. */
  53974. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53975. /**
  53976. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53977. */
  53978. this.emitRate = 100;
  53979. /**
  53980. * You can use gravity if you want to give an orientation to your particles.
  53981. */
  53982. this.gravity = BABYLON.Vector3.Zero();
  53983. /**
  53984. * Minimum power of emitting particles.
  53985. */
  53986. this.minEmitPower = 1;
  53987. /**
  53988. * Maximum power of emitting particles.
  53989. */
  53990. this.maxEmitPower = 1;
  53991. /**
  53992. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53993. * to override the particles.
  53994. */
  53995. this.forceDepthWrite = false;
  53996. this.id = name;
  53997. this.name = name;
  53998. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53999. this._engine = this._scene.getEngine();
  54000. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  54001. this._capacity = fullOptions.capacity;
  54002. this._activeCount = fullOptions.capacity;
  54003. this._currentActiveCount = 0;
  54004. this._scene.particleSystems.push(this);
  54005. this._updateEffectOptions = {
  54006. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  54007. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  54008. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  54009. uniformBuffersNames: [],
  54010. samplers: ["randomSampler"],
  54011. defines: "",
  54012. fallbacks: null,
  54013. onCompiled: null,
  54014. onError: null,
  54015. indexParameters: null,
  54016. maxSimultaneousLights: 0,
  54017. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  54018. };
  54019. // Random data
  54020. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  54021. var d = [];
  54022. for (var i = 0; i < maxTextureSize; ++i) {
  54023. d.push(Math.random());
  54024. d.push(Math.random());
  54025. d.push(Math.random());
  54026. d.push(Math.random());
  54027. }
  54028. 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);
  54029. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54030. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54031. this._randomTextureSize = maxTextureSize;
  54032. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  54033. }
  54034. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  54035. /**
  54036. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  54037. */
  54038. get: function () {
  54039. if (!BABYLON.Engine.LastCreatedEngine) {
  54040. return false;
  54041. }
  54042. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  54043. },
  54044. enumerable: true,
  54045. configurable: true
  54046. });
  54047. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  54048. /**
  54049. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54050. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54051. */
  54052. get: function () {
  54053. if (this.particleEmitterType.direction1) {
  54054. return this.particleEmitterType.direction1;
  54055. }
  54056. return BABYLON.Vector3.Zero();
  54057. },
  54058. set: function (value) {
  54059. if (this.particleEmitterType.direction1) {
  54060. this.particleEmitterType.direction1 = value;
  54061. }
  54062. },
  54063. enumerable: true,
  54064. configurable: true
  54065. });
  54066. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  54067. /**
  54068. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  54069. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54070. */
  54071. get: function () {
  54072. if (this.particleEmitterType.direction2) {
  54073. return this.particleEmitterType.direction2;
  54074. }
  54075. return BABYLON.Vector3.Zero();
  54076. },
  54077. set: function (value) {
  54078. if (this.particleEmitterType.direction2) {
  54079. this.particleEmitterType.direction2 = value;
  54080. }
  54081. },
  54082. enumerable: true,
  54083. configurable: true
  54084. });
  54085. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  54086. /**
  54087. * 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.
  54088. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54089. */
  54090. get: function () {
  54091. if (this.particleEmitterType.minEmitBox) {
  54092. return this.particleEmitterType.minEmitBox;
  54093. }
  54094. return BABYLON.Vector3.Zero();
  54095. },
  54096. set: function (value) {
  54097. if (this.particleEmitterType.minEmitBox) {
  54098. this.particleEmitterType.minEmitBox = value;
  54099. }
  54100. },
  54101. enumerable: true,
  54102. configurable: true
  54103. });
  54104. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  54105. /**
  54106. * 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.
  54107. * This only works when particleEmitterTyps is a BoxParticleEmitter
  54108. */
  54109. get: function () {
  54110. if (this.particleEmitterType.maxEmitBox) {
  54111. return this.particleEmitterType.maxEmitBox;
  54112. }
  54113. return BABYLON.Vector3.Zero();
  54114. },
  54115. set: function (value) {
  54116. if (this.particleEmitterType.maxEmitBox) {
  54117. this.particleEmitterType.maxEmitBox = value;
  54118. }
  54119. },
  54120. enumerable: true,
  54121. configurable: true
  54122. });
  54123. /**
  54124. * Gets the maximum number of particles active at the same time.
  54125. * @returns The max number of active particles.
  54126. */
  54127. GPUParticleSystem.prototype.getCapacity = function () {
  54128. return this._capacity;
  54129. };
  54130. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  54131. /**
  54132. * Gets or set the number of active particles
  54133. */
  54134. get: function () {
  54135. return this._activeCount;
  54136. },
  54137. set: function (value) {
  54138. this._activeCount = Math.min(value, this._capacity);
  54139. },
  54140. enumerable: true,
  54141. configurable: true
  54142. });
  54143. /**
  54144. * Is this system ready to be used/rendered
  54145. * @return true if the system is ready
  54146. */
  54147. GPUParticleSystem.prototype.isReady = function () {
  54148. if (!this._updateEffect) {
  54149. this._recreateUpdateEffect();
  54150. this._recreateRenderEffect();
  54151. return false;
  54152. }
  54153. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  54154. return false;
  54155. }
  54156. return true;
  54157. };
  54158. /**
  54159. * Gets Wether the system has been started.
  54160. * @returns True if it has been started, otherwise false.
  54161. */
  54162. GPUParticleSystem.prototype.isStarted = function () {
  54163. return this._started;
  54164. };
  54165. /**
  54166. * Starts the particle system and begins to emit.
  54167. */
  54168. GPUParticleSystem.prototype.start = function () {
  54169. this._started = true;
  54170. this._stopped = false;
  54171. };
  54172. /**
  54173. * Stops the particle system.
  54174. */
  54175. GPUParticleSystem.prototype.stop = function () {
  54176. this._stopped = true;
  54177. };
  54178. /**
  54179. * Remove all active particles
  54180. */
  54181. GPUParticleSystem.prototype.reset = function () {
  54182. this._releaseBuffers();
  54183. this._releaseVAOs();
  54184. this._currentActiveCount = 0;
  54185. this._targetIndex = 0;
  54186. };
  54187. /**
  54188. * Returns the string "GPUParticleSystem"
  54189. * @returns a string containing the class name
  54190. */
  54191. GPUParticleSystem.prototype.getClassName = function () {
  54192. return "GPUParticleSystem";
  54193. };
  54194. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  54195. var updateVertexBuffers = {};
  54196. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  54197. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  54198. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  54199. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  54200. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  54201. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  54202. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  54203. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  54204. this._engine.bindArrayBuffer(null);
  54205. return vao;
  54206. };
  54207. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  54208. var renderVertexBuffers = {};
  54209. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  54210. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  54211. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  54212. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  54213. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  54214. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  54215. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  54216. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  54217. this._engine.bindArrayBuffer(null);
  54218. return vao;
  54219. };
  54220. GPUParticleSystem.prototype._initialize = function (force) {
  54221. if (force === void 0) { force = false; }
  54222. if (this._buffer0 && !force) {
  54223. return;
  54224. }
  54225. var engine = this._scene.getEngine();
  54226. var data = new Array();
  54227. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  54228. // position
  54229. data.push(0.0);
  54230. data.push(0.0);
  54231. data.push(0.0);
  54232. // Age and life
  54233. data.push(0.0); // create the particle as a dead one to create a new one at start
  54234. data.push(0.0);
  54235. // Seed
  54236. data.push(Math.random());
  54237. // Size
  54238. data.push(0.0);
  54239. // color
  54240. data.push(0.0);
  54241. data.push(0.0);
  54242. data.push(0.0);
  54243. data.push(0.0);
  54244. // direction
  54245. data.push(0.0);
  54246. data.push(0.0);
  54247. data.push(0.0);
  54248. }
  54249. // Sprite data
  54250. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  54251. -0.5, 0.5, 0, 1,
  54252. -0.5, -0.5, 0, 0,
  54253. 0.5, -0.5, 1, 0]);
  54254. // Buffers
  54255. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  54256. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  54257. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  54258. // Update VAO
  54259. this._updateVAO = [];
  54260. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  54261. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  54262. // Render VAO
  54263. this._renderVAO = [];
  54264. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  54265. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  54266. // Links
  54267. this._sourceBuffer = this._buffer0;
  54268. this._targetBuffer = this._buffer1;
  54269. };
  54270. /** @ignore */
  54271. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  54272. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  54273. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  54274. return;
  54275. }
  54276. this._updateEffectOptions.defines = defines;
  54277. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  54278. };
  54279. /** @ignore */
  54280. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  54281. var defines = "";
  54282. if (this._scene.clipPlane) {
  54283. defines = "\n#define CLIPPLANE";
  54284. }
  54285. if (this._renderEffect && this._renderEffect.defines === defines) {
  54286. return;
  54287. }
  54288. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  54289. };
  54290. /**
  54291. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  54292. */
  54293. GPUParticleSystem.prototype.animate = function () {
  54294. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  54295. this._actualFrame += this._timeDelta;
  54296. if (!this._stopped) {
  54297. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  54298. this.stop();
  54299. }
  54300. }
  54301. };
  54302. /**
  54303. * Renders the particle system in its current state.
  54304. * @returns the current number of particles
  54305. */
  54306. GPUParticleSystem.prototype.render = function () {
  54307. if (!this._started) {
  54308. return 0;
  54309. }
  54310. this._recreateUpdateEffect();
  54311. this._recreateRenderEffect();
  54312. if (!this.isReady()) {
  54313. return 0;
  54314. }
  54315. if (this._currentRenderId === this._scene.getRenderId()) {
  54316. return 0;
  54317. }
  54318. this._currentRenderId = this._scene.getRenderId();
  54319. // Get everything ready to render
  54320. this._initialize();
  54321. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  54322. // Enable update effect
  54323. this._engine.enableEffect(this._updateEffect);
  54324. this._engine.setState(false);
  54325. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  54326. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  54327. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  54328. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  54329. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  54330. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  54331. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  54332. this._updateEffect.setDirectColor4("color1", this.color1);
  54333. this._updateEffect.setDirectColor4("color2", this.color2);
  54334. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  54335. this._updateEffect.setVector3("gravity", this.gravity);
  54336. if (this.particleEmitterType) {
  54337. this.particleEmitterType.applyToShader(this._updateEffect);
  54338. }
  54339. var emitterWM;
  54340. if (this.emitter.position) {
  54341. var emitterMesh = this.emitter;
  54342. emitterWM = emitterMesh.getWorldMatrix();
  54343. }
  54344. else {
  54345. var emitterPosition = this.emitter;
  54346. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  54347. }
  54348. this._updateEffect.setMatrix("emitterWM", emitterWM);
  54349. // Bind source VAO
  54350. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  54351. // Update
  54352. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  54353. this._engine.setRasterizerState(false);
  54354. this._engine.beginTransformFeedback();
  54355. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  54356. this._engine.endTransformFeedback();
  54357. this._engine.setRasterizerState(true);
  54358. this._engine.bindTransformFeedbackBuffer(null);
  54359. // Enable render effect
  54360. this._engine.enableEffect(this._renderEffect);
  54361. var viewMatrix = this._scene.getViewMatrix();
  54362. this._renderEffect.setMatrix("view", viewMatrix);
  54363. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  54364. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  54365. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  54366. if (this._scene.clipPlane) {
  54367. var clipPlane = this._scene.clipPlane;
  54368. var invView = viewMatrix.clone();
  54369. invView.invert();
  54370. this._renderEffect.setMatrix("invView", invView);
  54371. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  54372. }
  54373. // Draw order
  54374. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  54375. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  54376. }
  54377. else {
  54378. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54379. }
  54380. if (this.forceDepthWrite) {
  54381. this._engine.setDepthWrite(true);
  54382. }
  54383. // Bind source VAO
  54384. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  54385. // Render
  54386. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  54387. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54388. // Switch VAOs
  54389. this._targetIndex++;
  54390. if (this._targetIndex === 2) {
  54391. this._targetIndex = 0;
  54392. }
  54393. // Switch buffers
  54394. var tmpBuffer = this._sourceBuffer;
  54395. this._sourceBuffer = this._targetBuffer;
  54396. this._targetBuffer = tmpBuffer;
  54397. return this._currentActiveCount;
  54398. };
  54399. /**
  54400. * Rebuilds the particle system
  54401. */
  54402. GPUParticleSystem.prototype.rebuild = function () {
  54403. this._initialize(true);
  54404. };
  54405. GPUParticleSystem.prototype._releaseBuffers = function () {
  54406. if (this._buffer0) {
  54407. this._buffer0.dispose();
  54408. this._buffer0 = null;
  54409. }
  54410. if (this._buffer1) {
  54411. this._buffer1.dispose();
  54412. this._buffer1 = null;
  54413. }
  54414. if (this._spriteBuffer) {
  54415. this._spriteBuffer.dispose();
  54416. this._spriteBuffer = null;
  54417. }
  54418. };
  54419. GPUParticleSystem.prototype._releaseVAOs = function () {
  54420. if (!this._updateVAO) {
  54421. return;
  54422. }
  54423. for (var index = 0; index < this._updateVAO.length; index++) {
  54424. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  54425. }
  54426. this._updateVAO = [];
  54427. for (var index = 0; index < this._renderVAO.length; index++) {
  54428. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  54429. }
  54430. this._renderVAO = [];
  54431. };
  54432. /**
  54433. * Disposes the particle system and free the associated resources
  54434. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  54435. */
  54436. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  54437. if (disposeTexture === void 0) { disposeTexture = true; }
  54438. var index = this._scene.particleSystems.indexOf(this);
  54439. if (index > -1) {
  54440. this._scene.particleSystems.splice(index, 1);
  54441. }
  54442. this._releaseBuffers();
  54443. this._releaseVAOs();
  54444. if (this._randomTexture) {
  54445. this._randomTexture.dispose();
  54446. this._randomTexture = null;
  54447. }
  54448. if (disposeTexture && this.particleTexture) {
  54449. this.particleTexture.dispose();
  54450. this.particleTexture = null;
  54451. }
  54452. // Callback
  54453. this.onDisposeObservable.notifyObservers(this);
  54454. this.onDisposeObservable.clear();
  54455. };
  54456. /**
  54457. * Clones the particle system.
  54458. * @param name The name of the cloned object
  54459. * @param newEmitter The new emitter to use
  54460. * @returns the cloned particle system
  54461. */
  54462. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  54463. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  54464. BABYLON.Tools.DeepCopy(this, result);
  54465. if (newEmitter === undefined) {
  54466. newEmitter = this.emitter;
  54467. }
  54468. result.emitter = newEmitter;
  54469. if (this.particleTexture) {
  54470. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  54471. }
  54472. return result;
  54473. };
  54474. /**
  54475. * Serializes the particle system to a JSON object.
  54476. * @returns the JSON object
  54477. */
  54478. GPUParticleSystem.prototype.serialize = function () {
  54479. var serializationObject = {};
  54480. serializationObject.name = this.name;
  54481. serializationObject.id = this.id;
  54482. // Emitter
  54483. if (this.emitter.position) {
  54484. var emitterMesh = this.emitter;
  54485. serializationObject.emitterId = emitterMesh.id;
  54486. }
  54487. else {
  54488. var emitterPosition = this.emitter;
  54489. serializationObject.emitter = emitterPosition.asArray();
  54490. }
  54491. serializationObject.capacity = this.getCapacity();
  54492. if (this.particleTexture) {
  54493. serializationObject.textureName = this.particleTexture.name;
  54494. }
  54495. // Animations
  54496. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  54497. // Particle system
  54498. serializationObject.activeParticleCount = this.activeParticleCount;
  54499. serializationObject.randomTextureSize = this._randomTextureSize;
  54500. serializationObject.minSize = this.minSize;
  54501. serializationObject.maxSize = this.maxSize;
  54502. serializationObject.minEmitPower = this.minEmitPower;
  54503. serializationObject.maxEmitPower = this.maxEmitPower;
  54504. serializationObject.minLifeTime = this.minLifeTime;
  54505. serializationObject.maxLifeTime = this.maxLifeTime;
  54506. serializationObject.emitRate = this.emitRate;
  54507. serializationObject.gravity = this.gravity.asArray();
  54508. serializationObject.color1 = this.color1.asArray();
  54509. serializationObject.color2 = this.color2.asArray();
  54510. serializationObject.colorDead = this.colorDead.asArray();
  54511. serializationObject.updateSpeed = this.updateSpeed;
  54512. serializationObject.targetStopDuration = this.targetStopDuration;
  54513. serializationObject.blendMode = this.blendMode;
  54514. // Emitter
  54515. if (this.particleEmitterType) {
  54516. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  54517. }
  54518. return serializationObject;
  54519. };
  54520. /**
  54521. * Parses a JSON object to create a GPU particle system.
  54522. * @param parsedParticleSystem The JSON object to parse
  54523. * @param scene The scene to create the particle system in
  54524. * @param rootUrl The root url to use to load external dependencies like texture
  54525. * @returns the parsed GPU particle system
  54526. */
  54527. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  54528. var name = parsedParticleSystem.name;
  54529. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  54530. if (parsedParticleSystem.id) {
  54531. particleSystem.id = parsedParticleSystem.id;
  54532. }
  54533. // Texture
  54534. if (parsedParticleSystem.textureName) {
  54535. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  54536. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  54537. }
  54538. // Emitter
  54539. if (parsedParticleSystem.emitterId) {
  54540. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  54541. }
  54542. else {
  54543. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  54544. }
  54545. // Animations
  54546. if (parsedParticleSystem.animations) {
  54547. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  54548. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  54549. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  54550. }
  54551. }
  54552. // Particle system
  54553. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  54554. particleSystem.minSize = parsedParticleSystem.minSize;
  54555. particleSystem.maxSize = parsedParticleSystem.maxSize;
  54556. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  54557. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  54558. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  54559. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  54560. particleSystem.emitRate = parsedParticleSystem.emitRate;
  54561. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  54562. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  54563. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  54564. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  54565. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  54566. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  54567. particleSystem.blendMode = parsedParticleSystem.blendMode;
  54568. // Emitter
  54569. if (parsedParticleSystem.particleEmitterType) {
  54570. var emitterType = void 0;
  54571. switch (parsedParticleSystem.particleEmitterType.type) {
  54572. case "SphereEmitter":
  54573. emitterType = new BABYLON.SphereParticleEmitter();
  54574. break;
  54575. case "SphereDirectedParticleEmitter":
  54576. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  54577. break;
  54578. case "ConeEmitter":
  54579. emitterType = new BABYLON.ConeParticleEmitter();
  54580. break;
  54581. case "BoxEmitter":
  54582. default:
  54583. emitterType = new BABYLON.BoxParticleEmitter();
  54584. break;
  54585. }
  54586. emitterType.parse(parsedParticleSystem.particleEmitterType);
  54587. particleSystem.particleEmitterType = emitterType;
  54588. }
  54589. return particleSystem;
  54590. };
  54591. return GPUParticleSystem;
  54592. }());
  54593. BABYLON.GPUParticleSystem = GPUParticleSystem;
  54594. })(BABYLON || (BABYLON = {}));
  54595. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  54596. "use strict";
  54597. var BABYLON;
  54598. (function (BABYLON) {
  54599. /**
  54600. * Represents one particle of a solid particle system.
  54601. */
  54602. var SolidParticle = /** @class */ (function () {
  54603. /**
  54604. * Creates a Solid Particle object.
  54605. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  54606. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  54607. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  54608. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  54609. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  54610. * @param shapeId (integer) is the model shape identifier in the SPS.
  54611. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  54612. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  54613. */
  54614. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  54615. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  54616. /**
  54617. * particle global index
  54618. */
  54619. this.idx = 0;
  54620. /**
  54621. * The color of the particle
  54622. */
  54623. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54624. /**
  54625. * The world space position of the particle.
  54626. */
  54627. this.position = BABYLON.Vector3.Zero();
  54628. /**
  54629. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  54630. */
  54631. this.rotation = BABYLON.Vector3.Zero();
  54632. /**
  54633. * The scaling of the particle.
  54634. */
  54635. this.scaling = BABYLON.Vector3.One();
  54636. /**
  54637. * The uvs of the particle.
  54638. */
  54639. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  54640. /**
  54641. * The current speed of the particle.
  54642. */
  54643. this.velocity = BABYLON.Vector3.Zero();
  54644. /**
  54645. * The pivot point in the particle local space.
  54646. */
  54647. this.pivot = BABYLON.Vector3.Zero();
  54648. /**
  54649. * Must the particle be translated from its pivot point in its local space ?
  54650. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  54651. * Default : false
  54652. */
  54653. this.translateFromPivot = false;
  54654. /**
  54655. * Is the particle active or not ?
  54656. */
  54657. this.alive = true;
  54658. /**
  54659. * Is the particle visible or not ?
  54660. */
  54661. this.isVisible = true;
  54662. /**
  54663. * Index of this particle in the global "positions" array (Internal use)
  54664. */
  54665. this._pos = 0;
  54666. /**
  54667. * Index of this particle in the global "indices" array (Internal use)
  54668. */
  54669. this._ind = 0;
  54670. /**
  54671. * ModelShape id of this particle
  54672. */
  54673. this.shapeId = 0;
  54674. /**
  54675. * Index of the particle in its shape id (Internal use)
  54676. */
  54677. this.idxInShape = 0;
  54678. /**
  54679. * Still set as invisible in order to skip useless computations (Internal use)
  54680. */
  54681. this._stillInvisible = false;
  54682. /**
  54683. * Last computed particle rotation matrix
  54684. */
  54685. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  54686. /**
  54687. * Parent particle Id, if any.
  54688. * Default null.
  54689. */
  54690. this.parentId = null;
  54691. /**
  54692. * Internal global position in the SPS.
  54693. */
  54694. this._globalPosition = BABYLON.Vector3.Zero();
  54695. this.idx = particleIndex;
  54696. this._pos = positionIndex;
  54697. this._ind = indiceIndex;
  54698. this._model = model;
  54699. this.shapeId = shapeId;
  54700. this.idxInShape = idxInShape;
  54701. this._sps = sps;
  54702. if (modelBoundingInfo) {
  54703. this._modelBoundingInfo = modelBoundingInfo;
  54704. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  54705. }
  54706. }
  54707. Object.defineProperty(SolidParticle.prototype, "scale", {
  54708. /**
  54709. * Legacy support, changed scale to scaling
  54710. */
  54711. get: function () {
  54712. return this.scaling;
  54713. },
  54714. /**
  54715. * Legacy support, changed scale to scaling
  54716. */
  54717. set: function (scale) {
  54718. this.scaling = scale;
  54719. },
  54720. enumerable: true,
  54721. configurable: true
  54722. });
  54723. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  54724. /**
  54725. * Legacy support, changed quaternion to rotationQuaternion
  54726. */
  54727. get: function () {
  54728. return this.rotationQuaternion;
  54729. },
  54730. /**
  54731. * Legacy support, changed quaternion to rotationQuaternion
  54732. */
  54733. set: function (q) {
  54734. this.rotationQuaternion = q;
  54735. },
  54736. enumerable: true,
  54737. configurable: true
  54738. });
  54739. /**
  54740. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  54741. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  54742. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  54743. * @returns true if it intersects
  54744. */
  54745. SolidParticle.prototype.intersectsMesh = function (target) {
  54746. if (!this._boundingInfo || !target._boundingInfo) {
  54747. return false;
  54748. }
  54749. if (this._sps._bSphereOnly) {
  54750. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  54751. }
  54752. return this._boundingInfo.intersects(target._boundingInfo, false);
  54753. };
  54754. return SolidParticle;
  54755. }());
  54756. BABYLON.SolidParticle = SolidParticle;
  54757. /**
  54758. * Represents the shape of the model used by one particle of a solid particle system.
  54759. * SPS internal tool, don't use it manually.
  54760. */
  54761. var ModelShape = /** @class */ (function () {
  54762. /**
  54763. * 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.
  54764. * SPS internal tool, don't use it manually.
  54765. * @ignore
  54766. */
  54767. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  54768. /**
  54769. * length of the shape in the model indices array (internal use)
  54770. */
  54771. this._indicesLength = 0;
  54772. this.shapeID = id;
  54773. this._shape = shape;
  54774. this._indicesLength = indicesLength;
  54775. this._shapeUV = shapeUV;
  54776. this._positionFunction = posFunction;
  54777. this._vertexFunction = vtxFunction;
  54778. }
  54779. return ModelShape;
  54780. }());
  54781. BABYLON.ModelShape = ModelShape;
  54782. /**
  54783. * Represents a Depth Sorted Particle in the solid particle system.
  54784. */
  54785. var DepthSortedParticle = /** @class */ (function () {
  54786. function DepthSortedParticle() {
  54787. /**
  54788. * Index of the particle in the "indices" array
  54789. */
  54790. this.ind = 0;
  54791. /**
  54792. * Length of the particle shape in the "indices" array
  54793. */
  54794. this.indicesLength = 0;
  54795. /**
  54796. * Squared distance from the particle to the camera
  54797. */
  54798. this.sqDistance = 0.0;
  54799. }
  54800. return DepthSortedParticle;
  54801. }());
  54802. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54803. })(BABYLON || (BABYLON = {}));
  54804. //# sourceMappingURL=babylon.solidParticle.js.map
  54805. "use strict";
  54806. var BABYLON;
  54807. (function (BABYLON) {
  54808. /**
  54809. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54810. *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.
  54811. * The SPS is also a particle system. It provides some methods to manage the particles.
  54812. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54813. *
  54814. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54815. */
  54816. var SolidParticleSystem = /** @class */ (function () {
  54817. /**
  54818. * Creates a SPS (Solid Particle System) object.
  54819. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54820. * @param scene (Scene) is the scene in which the SPS is added.
  54821. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54822. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54823. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54824. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54825. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54826. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54827. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54828. */
  54829. function SolidParticleSystem(name, scene, options) {
  54830. /**
  54831. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54832. * Example : var p = SPS.particles[i];
  54833. */
  54834. this.particles = new Array();
  54835. /**
  54836. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54837. */
  54838. this.nbParticles = 0;
  54839. /**
  54840. * If the particles must ever face the camera (default false). Useful for planar particles.
  54841. */
  54842. this.billboard = false;
  54843. /**
  54844. * Recompute normals when adding a shape
  54845. */
  54846. this.recomputeNormals = true;
  54847. /**
  54848. * This a counter ofr your own usage. It's not set by any SPS functions.
  54849. */
  54850. this.counter = 0;
  54851. /**
  54852. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54853. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54854. */
  54855. this.vars = {};
  54856. /**
  54857. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54858. */
  54859. this._bSphereOnly = false;
  54860. /**
  54861. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54862. */
  54863. this._bSphereRadiusFactor = 1.0;
  54864. this._positions = new Array();
  54865. this._indices = new Array();
  54866. this._normals = new Array();
  54867. this._colors = new Array();
  54868. this._uvs = new Array();
  54869. this._index = 0; // indices index
  54870. this._updatable = true;
  54871. this._pickable = false;
  54872. this._isVisibilityBoxLocked = false;
  54873. this._alwaysVisible = false;
  54874. this._depthSort = false;
  54875. this._shapeCounter = 0;
  54876. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54877. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54878. this._computeParticleColor = true;
  54879. this._computeParticleTexture = true;
  54880. this._computeParticleRotation = true;
  54881. this._computeParticleVertex = false;
  54882. this._computeBoundingBox = false;
  54883. this._depthSortParticles = true;
  54884. this._cam_axisZ = BABYLON.Vector3.Zero();
  54885. this._cam_axisY = BABYLON.Vector3.Zero();
  54886. this._cam_axisX = BABYLON.Vector3.Zero();
  54887. this._axisZ = BABYLON.Axis.Z;
  54888. this._camDir = BABYLON.Vector3.Zero();
  54889. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54890. this._rotMatrix = new BABYLON.Matrix();
  54891. this._invertMatrix = new BABYLON.Matrix();
  54892. this._rotated = BABYLON.Vector3.Zero();
  54893. this._quaternion = new BABYLON.Quaternion();
  54894. this._vertex = BABYLON.Vector3.Zero();
  54895. this._normal = BABYLON.Vector3.Zero();
  54896. this._yaw = 0.0;
  54897. this._pitch = 0.0;
  54898. this._roll = 0.0;
  54899. this._halfroll = 0.0;
  54900. this._halfpitch = 0.0;
  54901. this._halfyaw = 0.0;
  54902. this._sinRoll = 0.0;
  54903. this._cosRoll = 0.0;
  54904. this._sinPitch = 0.0;
  54905. this._cosPitch = 0.0;
  54906. this._sinYaw = 0.0;
  54907. this._cosYaw = 0.0;
  54908. this._mustUnrotateFixedNormals = false;
  54909. this._minimum = BABYLON.Vector3.Zero();
  54910. this._maximum = BABYLON.Vector3.Zero();
  54911. this._minBbox = BABYLON.Vector3.Zero();
  54912. this._maxBbox = BABYLON.Vector3.Zero();
  54913. this._particlesIntersect = false;
  54914. this._depthSortFunction = function (p1, p2) {
  54915. return (p2.sqDistance - p1.sqDistance);
  54916. };
  54917. this._needs32Bits = false;
  54918. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54919. this._scaledPivot = BABYLON.Vector3.Zero();
  54920. this._particleHasParent = false;
  54921. this.name = name;
  54922. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54923. this._camera = scene.activeCamera;
  54924. this._pickable = options ? options.isPickable : false;
  54925. this._depthSort = options ? options.enableDepthSort : false;
  54926. this._particlesIntersect = options ? options.particleIntersection : false;
  54927. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54928. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54929. if (options && options.updatable) {
  54930. this._updatable = options.updatable;
  54931. }
  54932. else {
  54933. this._updatable = true;
  54934. }
  54935. if (this._pickable) {
  54936. this.pickedParticles = [];
  54937. }
  54938. if (this._depthSort) {
  54939. this.depthSortedParticles = [];
  54940. }
  54941. }
  54942. /**
  54943. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54944. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54945. * @returns the created mesh
  54946. */
  54947. SolidParticleSystem.prototype.buildMesh = function () {
  54948. if (this.nbParticles === 0) {
  54949. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54950. this.addShape(triangle, 1);
  54951. triangle.dispose();
  54952. }
  54953. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54954. this._positions32 = new Float32Array(this._positions);
  54955. this._uvs32 = new Float32Array(this._uvs);
  54956. this._colors32 = new Float32Array(this._colors);
  54957. if (this.recomputeNormals) {
  54958. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54959. }
  54960. this._normals32 = new Float32Array(this._normals);
  54961. this._fixedNormal32 = new Float32Array(this._normals);
  54962. if (this._mustUnrotateFixedNormals) {
  54963. this._unrotateFixedNormals();
  54964. }
  54965. var vertexData = new BABYLON.VertexData();
  54966. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54967. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54968. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54969. if (this._uvs32) {
  54970. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54971. ;
  54972. }
  54973. if (this._colors32) {
  54974. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54975. }
  54976. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54977. vertexData.applyToMesh(mesh, this._updatable);
  54978. this.mesh = mesh;
  54979. this.mesh.isPickable = this._pickable;
  54980. // free memory
  54981. if (!this._depthSort) {
  54982. this._indices = null;
  54983. }
  54984. this._positions = null;
  54985. this._normals = null;
  54986. this._uvs = null;
  54987. this._colors = null;
  54988. if (!this._updatable) {
  54989. this.particles.length = 0;
  54990. }
  54991. return mesh;
  54992. };
  54993. /**
  54994. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54995. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54996. * Thus the particles generated from `digest()` have their property `position` set yet.
  54997. * @param mesh ( Mesh ) is the mesh to be digested
  54998. * @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
  54999. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  55000. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  55001. * @returns the current SPS
  55002. */
  55003. SolidParticleSystem.prototype.digest = function (mesh, options) {
  55004. var size = (options && options.facetNb) || 1;
  55005. var number = (options && options.number) || 0;
  55006. var delta = (options && options.delta) || 0;
  55007. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55008. var meshInd = mesh.getIndices();
  55009. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55010. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55011. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55012. var f = 0; // facet counter
  55013. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  55014. // compute size from number
  55015. if (number) {
  55016. number = (number > totalFacets) ? totalFacets : number;
  55017. size = Math.round(totalFacets / number);
  55018. delta = 0;
  55019. }
  55020. else {
  55021. size = (size > totalFacets) ? totalFacets : size;
  55022. }
  55023. var facetPos = []; // submesh positions
  55024. var facetInd = []; // submesh indices
  55025. var facetUV = []; // submesh UV
  55026. var facetCol = []; // submesh colors
  55027. var barycenter = BABYLON.Vector3.Zero();
  55028. var sizeO = size;
  55029. while (f < totalFacets) {
  55030. size = sizeO + Math.floor((1 + delta) * Math.random());
  55031. if (f > totalFacets - size) {
  55032. size = totalFacets - f;
  55033. }
  55034. // reset temp arrays
  55035. facetPos.length = 0;
  55036. facetInd.length = 0;
  55037. facetUV.length = 0;
  55038. facetCol.length = 0;
  55039. // iterate over "size" facets
  55040. var fi = 0;
  55041. for (var j = f * 3; j < (f + size) * 3; j++) {
  55042. facetInd.push(fi);
  55043. var i = meshInd[j];
  55044. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  55045. if (meshUV) {
  55046. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  55047. }
  55048. if (meshCol) {
  55049. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  55050. }
  55051. fi++;
  55052. }
  55053. // create a model shape for each single particle
  55054. var idx = this.nbParticles;
  55055. var shape = this._posToShape(facetPos);
  55056. var shapeUV = this._uvsToShapeUV(facetUV);
  55057. // compute the barycenter of the shape
  55058. var v;
  55059. for (v = 0; v < shape.length; v++) {
  55060. barycenter.addInPlace(shape[v]);
  55061. }
  55062. barycenter.scaleInPlace(1 / shape.length);
  55063. // shift the shape from its barycenter to the origin
  55064. for (v = 0; v < shape.length; v++) {
  55065. shape[v].subtractInPlace(barycenter);
  55066. }
  55067. var bInfo;
  55068. if (this._particlesIntersect) {
  55069. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  55070. }
  55071. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  55072. // add the particle in the SPS
  55073. var currentPos = this._positions.length;
  55074. var currentInd = this._indices.length;
  55075. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  55076. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  55077. // initialize the particle position
  55078. this.particles[this.nbParticles].position.addInPlace(barycenter);
  55079. this._index += shape.length;
  55080. idx++;
  55081. this.nbParticles++;
  55082. this._shapeCounter++;
  55083. f += size;
  55084. }
  55085. return this;
  55086. };
  55087. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  55088. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  55089. var index = 0;
  55090. var idx = 0;
  55091. for (var p = 0; p < this.particles.length; p++) {
  55092. this._particle = this.particles[p];
  55093. this._shape = this._particle._model._shape;
  55094. if (this._particle.rotationQuaternion) {
  55095. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55096. }
  55097. else {
  55098. this._yaw = this._particle.rotation.y;
  55099. this._pitch = this._particle.rotation.x;
  55100. this._roll = this._particle.rotation.z;
  55101. this._quaternionRotationYPR();
  55102. }
  55103. this._quaternionToRotationMatrix();
  55104. this._rotMatrix.invertToRef(this._invertMatrix);
  55105. for (var pt = 0; pt < this._shape.length; pt++) {
  55106. idx = index + pt * 3;
  55107. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  55108. this._fixedNormal32[idx] = this._normal.x;
  55109. this._fixedNormal32[idx + 1] = this._normal.y;
  55110. this._fixedNormal32[idx + 2] = this._normal.z;
  55111. }
  55112. index = idx + 3;
  55113. }
  55114. };
  55115. //reset copy
  55116. SolidParticleSystem.prototype._resetCopy = function () {
  55117. this._copy.position.x = 0;
  55118. this._copy.position.y = 0;
  55119. this._copy.position.z = 0;
  55120. this._copy.rotation.x = 0;
  55121. this._copy.rotation.y = 0;
  55122. this._copy.rotation.z = 0;
  55123. this._copy.rotationQuaternion = null;
  55124. this._copy.scaling.x = 1.0;
  55125. this._copy.scaling.y = 1.0;
  55126. this._copy.scaling.z = 1.0;
  55127. this._copy.uvs.x = 0;
  55128. this._copy.uvs.y = 0;
  55129. this._copy.uvs.z = 1.0;
  55130. this._copy.uvs.w = 1.0;
  55131. this._copy.color = null;
  55132. this._copy.translateFromPivot = false;
  55133. };
  55134. // _meshBuilder : inserts the shape model in the global SPS mesh
  55135. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  55136. var i;
  55137. var u = 0;
  55138. var c = 0;
  55139. var n = 0;
  55140. this._resetCopy();
  55141. if (options && options.positionFunction) {
  55142. options.positionFunction(this._copy, idx, idxInShape);
  55143. this._mustUnrotateFixedNormals = true;
  55144. }
  55145. if (this._copy.rotationQuaternion) {
  55146. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55147. }
  55148. else {
  55149. this._yaw = this._copy.rotation.y;
  55150. this._pitch = this._copy.rotation.x;
  55151. this._roll = this._copy.rotation.z;
  55152. this._quaternionRotationYPR();
  55153. }
  55154. this._quaternionToRotationMatrix();
  55155. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  55156. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  55157. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  55158. if (this._copy.translateFromPivot) {
  55159. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  55160. }
  55161. else {
  55162. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  55163. }
  55164. for (i = 0; i < shape.length; i++) {
  55165. this._vertex.x = shape[i].x;
  55166. this._vertex.y = shape[i].y;
  55167. this._vertex.z = shape[i].z;
  55168. if (options && options.vertexFunction) {
  55169. options.vertexFunction(this._copy, this._vertex, i);
  55170. }
  55171. this._vertex.x *= this._copy.scaling.x;
  55172. this._vertex.y *= this._copy.scaling.y;
  55173. this._vertex.z *= this._copy.scaling.z;
  55174. this._vertex.x -= this._scaledPivot.x;
  55175. this._vertex.y -= this._scaledPivot.y;
  55176. this._vertex.z -= this._scaledPivot.z;
  55177. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55178. this._rotated.addInPlace(this._pivotBackTranslation);
  55179. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  55180. if (meshUV) {
  55181. 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);
  55182. u += 2;
  55183. }
  55184. if (this._copy.color) {
  55185. this._color = this._copy.color;
  55186. }
  55187. else if (meshCol && meshCol[c] !== undefined) {
  55188. this._color.r = meshCol[c];
  55189. this._color.g = meshCol[c + 1];
  55190. this._color.b = meshCol[c + 2];
  55191. this._color.a = meshCol[c + 3];
  55192. }
  55193. else {
  55194. this._color.r = 1.0;
  55195. this._color.g = 1.0;
  55196. this._color.b = 1.0;
  55197. this._color.a = 1.0;
  55198. }
  55199. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  55200. c += 4;
  55201. if (!this.recomputeNormals && meshNor) {
  55202. this._normal.x = meshNor[n];
  55203. this._normal.y = meshNor[n + 1];
  55204. this._normal.z = meshNor[n + 2];
  55205. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  55206. normals.push(this._normal.x, this._normal.y, this._normal.z);
  55207. n += 3;
  55208. }
  55209. }
  55210. for (i = 0; i < meshInd.length; i++) {
  55211. var current_ind = p + meshInd[i];
  55212. indices.push(current_ind);
  55213. if (current_ind > 65535) {
  55214. this._needs32Bits = true;
  55215. }
  55216. }
  55217. if (this._pickable) {
  55218. var nbfaces = meshInd.length / 3;
  55219. for (i = 0; i < nbfaces; i++) {
  55220. this.pickedParticles.push({ idx: idx, faceId: i });
  55221. }
  55222. }
  55223. if (this._depthSort) {
  55224. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  55225. }
  55226. return this._copy;
  55227. };
  55228. // returns a shape array from positions array
  55229. SolidParticleSystem.prototype._posToShape = function (positions) {
  55230. var shape = [];
  55231. for (var i = 0; i < positions.length; i += 3) {
  55232. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  55233. }
  55234. return shape;
  55235. };
  55236. // returns a shapeUV array from a Vector4 uvs
  55237. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  55238. var shapeUV = [];
  55239. if (uvs) {
  55240. for (var i = 0; i < uvs.length; i++)
  55241. shapeUV.push(uvs[i]);
  55242. }
  55243. return shapeUV;
  55244. };
  55245. // adds a new particle object in the particles array
  55246. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  55247. if (bInfo === void 0) { bInfo = null; }
  55248. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  55249. this.particles.push(sp);
  55250. return sp;
  55251. };
  55252. /**
  55253. * Adds some particles to the SPS from the model shape. Returns the shape id.
  55254. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  55255. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  55256. * @param nb (positive integer) the number of particles to be created from this model
  55257. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  55258. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  55259. * @returns the number of shapes in the system
  55260. */
  55261. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  55262. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55263. var meshInd = mesh.getIndices();
  55264. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55265. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55266. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55267. var bbInfo;
  55268. if (this._particlesIntersect) {
  55269. bbInfo = mesh.getBoundingInfo();
  55270. }
  55271. var shape = this._posToShape(meshPos);
  55272. var shapeUV = this._uvsToShapeUV(meshUV);
  55273. var posfunc = options ? options.positionFunction : null;
  55274. var vtxfunc = options ? options.vertexFunction : null;
  55275. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  55276. // particles
  55277. var sp;
  55278. var currentCopy;
  55279. var idx = this.nbParticles;
  55280. for (var i = 0; i < nb; i++) {
  55281. var currentPos = this._positions.length;
  55282. var currentInd = this._indices.length;
  55283. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  55284. if (this._updatable) {
  55285. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  55286. sp.position.copyFrom(currentCopy.position);
  55287. sp.rotation.copyFrom(currentCopy.rotation);
  55288. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  55289. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  55290. }
  55291. if (currentCopy.color && sp.color) {
  55292. sp.color.copyFrom(currentCopy.color);
  55293. }
  55294. sp.scaling.copyFrom(currentCopy.scaling);
  55295. sp.uvs.copyFrom(currentCopy.uvs);
  55296. }
  55297. this._index += shape.length;
  55298. idx++;
  55299. }
  55300. this.nbParticles += nb;
  55301. this._shapeCounter++;
  55302. return this._shapeCounter - 1;
  55303. };
  55304. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  55305. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  55306. this._resetCopy();
  55307. if (particle._model._positionFunction) {
  55308. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  55309. }
  55310. if (this._copy.rotationQuaternion) {
  55311. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  55312. }
  55313. else {
  55314. this._yaw = this._copy.rotation.y;
  55315. this._pitch = this._copy.rotation.x;
  55316. this._roll = this._copy.rotation.z;
  55317. this._quaternionRotationYPR();
  55318. }
  55319. this._quaternionToRotationMatrix();
  55320. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  55321. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  55322. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  55323. if (this._copy.translateFromPivot) {
  55324. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  55325. }
  55326. else {
  55327. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  55328. }
  55329. this._shape = particle._model._shape;
  55330. for (var pt = 0; pt < this._shape.length; pt++) {
  55331. this._vertex.x = this._shape[pt].x;
  55332. this._vertex.y = this._shape[pt].y;
  55333. this._vertex.z = this._shape[pt].z;
  55334. if (particle._model._vertexFunction) {
  55335. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  55336. }
  55337. this._vertex.x *= this._copy.scaling.x;
  55338. this._vertex.y *= this._copy.scaling.y;
  55339. this._vertex.z *= this._copy.scaling.z;
  55340. this._vertex.x -= this._scaledPivot.x;
  55341. this._vertex.y -= this._scaledPivot.y;
  55342. this._vertex.z -= this._scaledPivot.z;
  55343. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  55344. this._rotated.addInPlace(this._pivotBackTranslation);
  55345. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  55346. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  55347. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  55348. }
  55349. particle.position.x = 0.0;
  55350. particle.position.y = 0.0;
  55351. particle.position.z = 0.0;
  55352. particle.rotation.x = 0.0;
  55353. particle.rotation.y = 0.0;
  55354. particle.rotation.z = 0.0;
  55355. particle.rotationQuaternion = null;
  55356. particle.scaling.x = 1.0;
  55357. particle.scaling.y = 1.0;
  55358. particle.scaling.z = 1.0;
  55359. particle.uvs.x = 0.0;
  55360. particle.uvs.y = 0.0;
  55361. particle.uvs.z = 1.0;
  55362. particle.uvs.w = 1.0;
  55363. particle.pivot.x = 0.0;
  55364. particle.pivot.y = 0.0;
  55365. particle.pivot.z = 0.0;
  55366. particle.translateFromPivot = false;
  55367. particle.parentId = null;
  55368. };
  55369. /**
  55370. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  55371. * @returns the SPS.
  55372. */
  55373. SolidParticleSystem.prototype.rebuildMesh = function () {
  55374. for (var p = 0; p < this.particles.length; p++) {
  55375. this._rebuildParticle(this.particles[p]);
  55376. }
  55377. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55378. return this;
  55379. };
  55380. /**
  55381. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  55382. * This method calls `updateParticle()` for each particle of the SPS.
  55383. * For an animated SPS, it is usually called within the render loop.
  55384. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  55385. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  55386. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  55387. * @returns the SPS.
  55388. */
  55389. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  55390. if (start === void 0) { start = 0; }
  55391. if (end === void 0) { end = this.nbParticles - 1; }
  55392. if (update === void 0) { update = true; }
  55393. if (!this._updatable) {
  55394. return this;
  55395. }
  55396. // custom beforeUpdate
  55397. this.beforeUpdateParticles(start, end, update);
  55398. this._cam_axisX.x = 1.0;
  55399. this._cam_axisX.y = 0.0;
  55400. this._cam_axisX.z = 0.0;
  55401. this._cam_axisY.x = 0.0;
  55402. this._cam_axisY.y = 1.0;
  55403. this._cam_axisY.z = 0.0;
  55404. this._cam_axisZ.x = 0.0;
  55405. this._cam_axisZ.y = 0.0;
  55406. this._cam_axisZ.z = 1.0;
  55407. // cases when the World Matrix is to be computed first
  55408. if (this.billboard || this._depthSort) {
  55409. this.mesh.computeWorldMatrix(true);
  55410. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  55411. }
  55412. // if the particles will always face the camera
  55413. if (this.billboard) {
  55414. // compute the camera position and un-rotate it by the current mesh rotation
  55415. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  55416. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  55417. this._cam_axisZ.normalize();
  55418. // same for camera up vector extracted from the cam view matrix
  55419. var view = this._camera.getViewMatrix(true);
  55420. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  55421. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  55422. this._cam_axisY.normalize();
  55423. this._cam_axisX.normalize();
  55424. }
  55425. // if depthSort, compute the camera global position in the mesh local system
  55426. if (this._depthSort) {
  55427. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  55428. }
  55429. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  55430. var idx = 0; // current position index in the global array positions32
  55431. var index = 0; // position start index in the global array positions32 of the current particle
  55432. var colidx = 0; // current color index in the global array colors32
  55433. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  55434. var uvidx = 0; // current uv index in the global array uvs32
  55435. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  55436. var pt = 0; // current index in the particle model shape
  55437. if (this.mesh.isFacetDataEnabled) {
  55438. this._computeBoundingBox = true;
  55439. }
  55440. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  55441. if (this._computeBoundingBox) {
  55442. if (start == 0 && end == this.nbParticles - 1) {
  55443. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  55444. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  55445. }
  55446. else {
  55447. if (this.mesh._boundingInfo) {
  55448. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  55449. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  55450. }
  55451. }
  55452. }
  55453. // particle loop
  55454. index = this.particles[start]._pos;
  55455. var vpos = (index / 3) | 0;
  55456. colorIndex = vpos * 4;
  55457. uvIndex = vpos * 2;
  55458. for (var p = start; p <= end; p++) {
  55459. this._particle = this.particles[p];
  55460. this._shape = this._particle._model._shape;
  55461. this._shapeUV = this._particle._model._shapeUV;
  55462. // call to custom user function to update the particle properties
  55463. this.updateParticle(this._particle);
  55464. // camera-particle distance for depth sorting
  55465. if (this._depthSort && this._depthSortParticles) {
  55466. var dsp = this.depthSortedParticles[p];
  55467. dsp.ind = this._particle._ind;
  55468. dsp.indicesLength = this._particle._model._indicesLength;
  55469. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  55470. }
  55471. // skip the computations for inactive or already invisible particles
  55472. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  55473. // increment indexes for the next particle
  55474. pt = this._shape.length;
  55475. index += pt * 3;
  55476. colorIndex += pt * 4;
  55477. uvIndex += pt * 2;
  55478. continue;
  55479. }
  55480. if (this._particle.isVisible) {
  55481. this._particle._stillInvisible = false; // un-mark permanent invisibility
  55482. this._particleHasParent = (this._particle.parentId !== null);
  55483. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  55484. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  55485. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  55486. // particle rotation matrix
  55487. if (this.billboard) {
  55488. this._particle.rotation.x = 0.0;
  55489. this._particle.rotation.y = 0.0;
  55490. }
  55491. if (this._computeParticleRotation || this.billboard) {
  55492. if (this._particle.rotationQuaternion) {
  55493. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  55494. }
  55495. else {
  55496. this._yaw = this._particle.rotation.y;
  55497. this._pitch = this._particle.rotation.x;
  55498. this._roll = this._particle.rotation.z;
  55499. this._quaternionRotationYPR();
  55500. }
  55501. this._quaternionToRotationMatrix();
  55502. }
  55503. if (this._particleHasParent) {
  55504. this._parent = this.particles[this._particle.parentId];
  55505. 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];
  55506. 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];
  55507. 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];
  55508. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  55509. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  55510. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  55511. if (this._computeParticleRotation || this.billboard) {
  55512. 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];
  55513. 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];
  55514. 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];
  55515. 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];
  55516. 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];
  55517. 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];
  55518. 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];
  55519. 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];
  55520. 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];
  55521. }
  55522. }
  55523. else {
  55524. this._particle._globalPosition.x = this._particle.position.x;
  55525. this._particle._globalPosition.y = this._particle.position.y;
  55526. this._particle._globalPosition.z = this._particle.position.z;
  55527. if (this._computeParticleRotation || this.billboard) {
  55528. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  55529. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  55530. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  55531. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  55532. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  55533. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  55534. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  55535. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  55536. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  55537. }
  55538. }
  55539. if (this._particle.translateFromPivot) {
  55540. this._pivotBackTranslation.x = 0.0;
  55541. this._pivotBackTranslation.y = 0.0;
  55542. this._pivotBackTranslation.z = 0.0;
  55543. }
  55544. else {
  55545. this._pivotBackTranslation.x = this._scaledPivot.x;
  55546. this._pivotBackTranslation.y = this._scaledPivot.y;
  55547. this._pivotBackTranslation.z = this._scaledPivot.z;
  55548. }
  55549. // particle vertex loop
  55550. for (pt = 0; pt < this._shape.length; pt++) {
  55551. idx = index + pt * 3;
  55552. colidx = colorIndex + pt * 4;
  55553. uvidx = uvIndex + pt * 2;
  55554. this._vertex.x = this._shape[pt].x;
  55555. this._vertex.y = this._shape[pt].y;
  55556. this._vertex.z = this._shape[pt].z;
  55557. if (this._computeParticleVertex) {
  55558. this.updateParticleVertex(this._particle, this._vertex, pt);
  55559. }
  55560. // positions
  55561. this._vertex.x *= this._particle.scaling.x;
  55562. this._vertex.y *= this._particle.scaling.y;
  55563. this._vertex.z *= this._particle.scaling.z;
  55564. this._vertex.x -= this._scaledPivot.x;
  55565. this._vertex.y -= this._scaledPivot.y;
  55566. this._vertex.z -= this._scaledPivot.z;
  55567. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  55568. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  55569. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  55570. this._rotated.x += this._pivotBackTranslation.x;
  55571. this._rotated.y += this._pivotBackTranslation.y;
  55572. this._rotated.z += this._pivotBackTranslation.z;
  55573. 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;
  55574. 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;
  55575. 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;
  55576. if (this._computeBoundingBox) {
  55577. if (this._positions32[idx] < this._minimum.x) {
  55578. this._minimum.x = this._positions32[idx];
  55579. }
  55580. if (this._positions32[idx] > this._maximum.x) {
  55581. this._maximum.x = this._positions32[idx];
  55582. }
  55583. if (this._positions32[idx + 1] < this._minimum.y) {
  55584. this._minimum.y = this._positions32[idx + 1];
  55585. }
  55586. if (this._positions32[idx + 1] > this._maximum.y) {
  55587. this._maximum.y = this._positions32[idx + 1];
  55588. }
  55589. if (this._positions32[idx + 2] < this._minimum.z) {
  55590. this._minimum.z = this._positions32[idx + 2];
  55591. }
  55592. if (this._positions32[idx + 2] > this._maximum.z) {
  55593. this._maximum.z = this._positions32[idx + 2];
  55594. }
  55595. }
  55596. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  55597. if (!this._computeParticleVertex) {
  55598. this._normal.x = this._fixedNormal32[idx];
  55599. this._normal.y = this._fixedNormal32[idx + 1];
  55600. this._normal.z = this._fixedNormal32[idx + 2];
  55601. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  55602. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  55603. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  55604. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  55605. 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;
  55606. 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;
  55607. }
  55608. if (this._computeParticleColor && this._particle.color) {
  55609. this._colors32[colidx] = this._particle.color.r;
  55610. this._colors32[colidx + 1] = this._particle.color.g;
  55611. this._colors32[colidx + 2] = this._particle.color.b;
  55612. this._colors32[colidx + 3] = this._particle.color.a;
  55613. }
  55614. if (this._computeParticleTexture) {
  55615. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55616. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55617. }
  55618. }
  55619. }
  55620. else {
  55621. this._particle._stillInvisible = true; // mark the particle as invisible
  55622. for (pt = 0; pt < this._shape.length; pt++) {
  55623. idx = index + pt * 3;
  55624. colidx = colorIndex + pt * 4;
  55625. uvidx = uvIndex + pt * 2;
  55626. this._positions32[idx] = 0.0;
  55627. this._positions32[idx + 1] = 0.0;
  55628. this._positions32[idx + 2] = 0.0;
  55629. this._normals32[idx] = 0.0;
  55630. this._normals32[idx + 1] = 0.0;
  55631. this._normals32[idx + 2] = 0.0;
  55632. if (this._computeParticleColor && this._particle.color) {
  55633. this._colors32[colidx] = this._particle.color.r;
  55634. this._colors32[colidx + 1] = this._particle.color.g;
  55635. this._colors32[colidx + 2] = this._particle.color.b;
  55636. this._colors32[colidx + 3] = this._particle.color.a;
  55637. }
  55638. if (this._computeParticleTexture) {
  55639. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  55640. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  55641. }
  55642. }
  55643. }
  55644. // if the particle intersections must be computed : update the bbInfo
  55645. if (this._particlesIntersect) {
  55646. var bInfo = this._particle._boundingInfo;
  55647. var bBox = bInfo.boundingBox;
  55648. var bSphere = bInfo.boundingSphere;
  55649. if (!this._bSphereOnly) {
  55650. // place, scale and rotate the particle bbox within the SPS local system, then update it
  55651. for (var b = 0; b < bBox.vectors.length; b++) {
  55652. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  55653. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  55654. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  55655. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  55656. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  55657. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  55658. 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;
  55659. 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;
  55660. 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;
  55661. }
  55662. bBox._update(this.mesh._worldMatrix);
  55663. }
  55664. // place and scale the particle bouding sphere in the SPS local system, then update it
  55665. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  55666. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  55667. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  55668. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  55669. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  55670. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  55671. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  55672. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  55673. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  55674. 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));
  55675. bSphere._update(this.mesh._worldMatrix);
  55676. }
  55677. // increment indexes for the next particle
  55678. index = idx + 3;
  55679. colorIndex = colidx + 4;
  55680. uvIndex = uvidx + 2;
  55681. }
  55682. // if the VBO must be updated
  55683. if (update) {
  55684. if (this._computeParticleColor) {
  55685. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  55686. }
  55687. if (this._computeParticleTexture) {
  55688. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  55689. }
  55690. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  55691. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  55692. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  55693. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  55694. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  55695. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  55696. for (var i = 0; i < this._normals32.length; i++) {
  55697. this._fixedNormal32[i] = this._normals32[i];
  55698. }
  55699. }
  55700. if (!this.mesh.areNormalsFrozen) {
  55701. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  55702. }
  55703. }
  55704. if (this._depthSort && this._depthSortParticles) {
  55705. this.depthSortedParticles.sort(this._depthSortFunction);
  55706. var dspl = this.depthSortedParticles.length;
  55707. var sorted = 0;
  55708. var lind = 0;
  55709. var sind = 0;
  55710. var sid = 0;
  55711. for (sorted = 0; sorted < dspl; sorted++) {
  55712. lind = this.depthSortedParticles[sorted].indicesLength;
  55713. sind = this.depthSortedParticles[sorted].ind;
  55714. for (var i = 0; i < lind; i++) {
  55715. this._indices32[sid] = this._indices[sind + i];
  55716. sid++;
  55717. }
  55718. }
  55719. this.mesh.updateIndices(this._indices32);
  55720. }
  55721. }
  55722. if (this._computeBoundingBox) {
  55723. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  55724. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  55725. }
  55726. this.afterUpdateParticles(start, end, update);
  55727. return this;
  55728. };
  55729. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  55730. this._halfroll = this._roll * 0.5;
  55731. this._halfpitch = this._pitch * 0.5;
  55732. this._halfyaw = this._yaw * 0.5;
  55733. this._sinRoll = Math.sin(this._halfroll);
  55734. this._cosRoll = Math.cos(this._halfroll);
  55735. this._sinPitch = Math.sin(this._halfpitch);
  55736. this._cosPitch = Math.cos(this._halfpitch);
  55737. this._sinYaw = Math.sin(this._halfyaw);
  55738. this._cosYaw = Math.cos(this._halfyaw);
  55739. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  55740. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  55741. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  55742. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  55743. };
  55744. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  55745. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  55746. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  55747. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  55748. this._rotMatrix.m[3] = 0;
  55749. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  55750. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  55751. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  55752. this._rotMatrix.m[7] = 0;
  55753. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  55754. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  55755. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  55756. this._rotMatrix.m[11] = 0;
  55757. this._rotMatrix.m[12] = 0;
  55758. this._rotMatrix.m[13] = 0;
  55759. this._rotMatrix.m[14] = 0;
  55760. this._rotMatrix.m[15] = 1.0;
  55761. };
  55762. /**
  55763. * Disposes the SPS.
  55764. */
  55765. SolidParticleSystem.prototype.dispose = function () {
  55766. this.mesh.dispose();
  55767. this.vars = null;
  55768. // drop references to internal big arrays for the GC
  55769. this._positions = null;
  55770. this._indices = null;
  55771. this._normals = null;
  55772. this._uvs = null;
  55773. this._colors = null;
  55774. this._indices32 = null;
  55775. this._positions32 = null;
  55776. this._normals32 = null;
  55777. this._fixedNormal32 = null;
  55778. this._uvs32 = null;
  55779. this._colors32 = null;
  55780. this.pickedParticles = null;
  55781. };
  55782. /**
  55783. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55784. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55785. * @returns the SPS.
  55786. */
  55787. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55788. if (!this._isVisibilityBoxLocked) {
  55789. this.mesh.refreshBoundingInfo();
  55790. }
  55791. return this;
  55792. };
  55793. /**
  55794. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55795. * @param size the size (float) of the visibility box
  55796. * note : this doesn't lock the SPS mesh bounding box.
  55797. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55798. */
  55799. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55800. var vis = size / 2;
  55801. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55802. };
  55803. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55804. /**
  55805. * Gets whether the SPS as always visible or not
  55806. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55807. */
  55808. get: function () {
  55809. return this._alwaysVisible;
  55810. },
  55811. /**
  55812. * Sets the SPS as always visible or not
  55813. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55814. */
  55815. set: function (val) {
  55816. this._alwaysVisible = val;
  55817. this.mesh.alwaysSelectAsActiveMesh = val;
  55818. },
  55819. enumerable: true,
  55820. configurable: true
  55821. });
  55822. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55823. /**
  55824. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55825. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55826. */
  55827. get: function () {
  55828. return this._isVisibilityBoxLocked;
  55829. },
  55830. /**
  55831. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55832. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55833. */
  55834. set: function (val) {
  55835. this._isVisibilityBoxLocked = val;
  55836. var boundingInfo = this.mesh.getBoundingInfo();
  55837. boundingInfo.isLocked = val;
  55838. },
  55839. enumerable: true,
  55840. configurable: true
  55841. });
  55842. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55843. /**
  55844. * Gets if `setParticles()` computes the particle rotations or not.
  55845. * Default value : true. The SPS is faster when it's set to false.
  55846. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55847. */
  55848. get: function () {
  55849. return this._computeParticleRotation;
  55850. },
  55851. /**
  55852. * Tells to `setParticles()` to compute the particle rotations or not.
  55853. * Default value : true. The SPS is faster when it's set to false.
  55854. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55855. */
  55856. set: function (val) {
  55857. this._computeParticleRotation = val;
  55858. },
  55859. enumerable: true,
  55860. configurable: true
  55861. });
  55862. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55863. /**
  55864. * Gets if `setParticles()` computes the particle colors or not.
  55865. * Default value : true. The SPS is faster when it's set to false.
  55866. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55867. */
  55868. get: function () {
  55869. return this._computeParticleColor;
  55870. },
  55871. /**
  55872. * Tells to `setParticles()` to compute the particle colors or not.
  55873. * Default value : true. The SPS is faster when it's set to false.
  55874. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55875. */
  55876. set: function (val) {
  55877. this._computeParticleColor = val;
  55878. },
  55879. enumerable: true,
  55880. configurable: true
  55881. });
  55882. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55883. /**
  55884. * Gets if `setParticles()` computes the particle textures or not.
  55885. * Default value : true. The SPS is faster when it's set to false.
  55886. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55887. */
  55888. get: function () {
  55889. return this._computeParticleTexture;
  55890. },
  55891. set: function (val) {
  55892. this._computeParticleTexture = val;
  55893. },
  55894. enumerable: true,
  55895. configurable: true
  55896. });
  55897. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55898. /**
  55899. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55900. * Default value : false. The SPS is faster when it's set to false.
  55901. * Note : the particle custom vertex positions aren't stored values.
  55902. */
  55903. get: function () {
  55904. return this._computeParticleVertex;
  55905. },
  55906. /**
  55907. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55908. * Default value : false. The SPS is faster when it's set to false.
  55909. * Note : the particle custom vertex positions aren't stored values.
  55910. */
  55911. set: function (val) {
  55912. this._computeParticleVertex = val;
  55913. },
  55914. enumerable: true,
  55915. configurable: true
  55916. });
  55917. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55918. /**
  55919. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55920. */
  55921. get: function () {
  55922. return this._computeBoundingBox;
  55923. },
  55924. /**
  55925. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55926. */
  55927. set: function (val) {
  55928. this._computeBoundingBox = val;
  55929. },
  55930. enumerable: true,
  55931. configurable: true
  55932. });
  55933. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55934. /**
  55935. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55936. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55937. * Default : `true`
  55938. */
  55939. get: function () {
  55940. return this._depthSortParticles;
  55941. },
  55942. /**
  55943. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55944. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55945. * Default : `true`
  55946. */
  55947. set: function (val) {
  55948. this._depthSortParticles = val;
  55949. },
  55950. enumerable: true,
  55951. configurable: true
  55952. });
  55953. // =======================================================================
  55954. // Particle behavior logic
  55955. // these following methods may be overwritten by the user to fit his needs
  55956. /**
  55957. * This function does nothing. It may be overwritten to set all the particle first values.
  55958. * The SPS doesn't call this function, you may have to call it by your own.
  55959. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55960. */
  55961. SolidParticleSystem.prototype.initParticles = function () {
  55962. };
  55963. /**
  55964. * This function does nothing. It may be overwritten to recycle a particle.
  55965. * The SPS doesn't call this function, you may have to call it by your own.
  55966. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55967. * @param particle The particle to recycle
  55968. * @returns the recycled particle
  55969. */
  55970. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55971. return particle;
  55972. };
  55973. /**
  55974. * Updates a particle : this function should be overwritten by the user.
  55975. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55976. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55977. * @example : just set a particle position or velocity and recycle conditions
  55978. * @param particle The particle to update
  55979. * @returns the updated particle
  55980. */
  55981. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55982. return particle;
  55983. };
  55984. /**
  55985. * Updates a vertex of a particle : it can be overwritten by the user.
  55986. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55987. * @param particle the current particle
  55988. * @param vertex the current index of the current particle
  55989. * @param pt the index of the current vertex in the particle shape
  55990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55991. * @example : just set a vertex particle position
  55992. * @returns the updated vertex
  55993. */
  55994. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55995. return vertex;
  55996. };
  55997. /**
  55998. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55999. * This does nothing and may be overwritten by the user.
  56000. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56001. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56002. * @param update the boolean update value actually passed to setParticles()
  56003. */
  56004. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  56005. };
  56006. /**
  56007. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  56008. * This will be passed three parameters.
  56009. * This does nothing and may be overwritten by the user.
  56010. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56011. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  56012. * @param update the boolean update value actually passed to setParticles()
  56013. */
  56014. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  56015. };
  56016. return SolidParticleSystem;
  56017. }());
  56018. BABYLON.SolidParticleSystem = SolidParticleSystem;
  56019. })(BABYLON || (BABYLON = {}));
  56020. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  56021. "use strict";
  56022. var BABYLON;
  56023. (function (BABYLON) {
  56024. var ShaderMaterial = /** @class */ (function (_super) {
  56025. __extends(ShaderMaterial, _super);
  56026. function ShaderMaterial(name, scene, shaderPath, options) {
  56027. var _this = _super.call(this, name, scene) || this;
  56028. _this._textures = {};
  56029. _this._textureArrays = {};
  56030. _this._floats = {};
  56031. _this._ints = {};
  56032. _this._floatsArrays = {};
  56033. _this._colors3 = {};
  56034. _this._colors3Arrays = {};
  56035. _this._colors4 = {};
  56036. _this._vectors2 = {};
  56037. _this._vectors3 = {};
  56038. _this._vectors4 = {};
  56039. _this._matrices = {};
  56040. _this._matrices3x3 = {};
  56041. _this._matrices2x2 = {};
  56042. _this._vectors2Arrays = {};
  56043. _this._vectors3Arrays = {};
  56044. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  56045. _this._shaderPath = shaderPath;
  56046. options.needAlphaBlending = options.needAlphaBlending || false;
  56047. options.needAlphaTesting = options.needAlphaTesting || false;
  56048. options.attributes = options.attributes || ["position", "normal", "uv"];
  56049. options.uniforms = options.uniforms || ["worldViewProjection"];
  56050. options.uniformBuffers = options.uniformBuffers || [];
  56051. options.samplers = options.samplers || [];
  56052. options.defines = options.defines || [];
  56053. _this._options = options;
  56054. return _this;
  56055. }
  56056. ShaderMaterial.prototype.getClassName = function () {
  56057. return "ShaderMaterial";
  56058. };
  56059. ShaderMaterial.prototype.needAlphaBlending = function () {
  56060. return this._options.needAlphaBlending;
  56061. };
  56062. ShaderMaterial.prototype.needAlphaTesting = function () {
  56063. return this._options.needAlphaTesting;
  56064. };
  56065. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  56066. if (this._options.uniforms.indexOf(uniformName) === -1) {
  56067. this._options.uniforms.push(uniformName);
  56068. }
  56069. };
  56070. ShaderMaterial.prototype.setTexture = function (name, texture) {
  56071. if (this._options.samplers.indexOf(name) === -1) {
  56072. this._options.samplers.push(name);
  56073. }
  56074. this._textures[name] = texture;
  56075. return this;
  56076. };
  56077. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  56078. if (this._options.samplers.indexOf(name) === -1) {
  56079. this._options.samplers.push(name);
  56080. }
  56081. this._checkUniform(name);
  56082. this._textureArrays[name] = textures;
  56083. return this;
  56084. };
  56085. ShaderMaterial.prototype.setFloat = function (name, value) {
  56086. this._checkUniform(name);
  56087. this._floats[name] = value;
  56088. return this;
  56089. };
  56090. ShaderMaterial.prototype.setInt = function (name, value) {
  56091. this._checkUniform(name);
  56092. this._ints[name] = value;
  56093. return this;
  56094. };
  56095. ShaderMaterial.prototype.setFloats = function (name, value) {
  56096. this._checkUniform(name);
  56097. this._floatsArrays[name] = value;
  56098. return this;
  56099. };
  56100. ShaderMaterial.prototype.setColor3 = function (name, value) {
  56101. this._checkUniform(name);
  56102. this._colors3[name] = value;
  56103. return this;
  56104. };
  56105. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  56106. this._checkUniform(name);
  56107. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  56108. color.toArray(arr, arr.length);
  56109. return arr;
  56110. }, []);
  56111. return this;
  56112. };
  56113. ShaderMaterial.prototype.setColor4 = function (name, value) {
  56114. this._checkUniform(name);
  56115. this._colors4[name] = value;
  56116. return this;
  56117. };
  56118. ShaderMaterial.prototype.setVector2 = function (name, value) {
  56119. this._checkUniform(name);
  56120. this._vectors2[name] = value;
  56121. return this;
  56122. };
  56123. ShaderMaterial.prototype.setVector3 = function (name, value) {
  56124. this._checkUniform(name);
  56125. this._vectors3[name] = value;
  56126. return this;
  56127. };
  56128. ShaderMaterial.prototype.setVector4 = function (name, value) {
  56129. this._checkUniform(name);
  56130. this._vectors4[name] = value;
  56131. return this;
  56132. };
  56133. ShaderMaterial.prototype.setMatrix = function (name, value) {
  56134. this._checkUniform(name);
  56135. this._matrices[name] = value;
  56136. return this;
  56137. };
  56138. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  56139. this._checkUniform(name);
  56140. this._matrices3x3[name] = value;
  56141. return this;
  56142. };
  56143. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  56144. this._checkUniform(name);
  56145. this._matrices2x2[name] = value;
  56146. return this;
  56147. };
  56148. ShaderMaterial.prototype.setArray2 = function (name, value) {
  56149. this._checkUniform(name);
  56150. this._vectors2Arrays[name] = value;
  56151. return this;
  56152. };
  56153. ShaderMaterial.prototype.setArray3 = function (name, value) {
  56154. this._checkUniform(name);
  56155. this._vectors3Arrays[name] = value;
  56156. return this;
  56157. };
  56158. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  56159. if (!mesh) {
  56160. return true;
  56161. }
  56162. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  56163. return false;
  56164. }
  56165. return false;
  56166. };
  56167. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  56168. var scene = this.getScene();
  56169. var engine = scene.getEngine();
  56170. if (!this.checkReadyOnEveryCall) {
  56171. if (this._renderId === scene.getRenderId()) {
  56172. if (this._checkCache(scene, mesh, useInstances)) {
  56173. return true;
  56174. }
  56175. }
  56176. }
  56177. // Instances
  56178. var defines = [];
  56179. var attribs = [];
  56180. var fallbacks = new BABYLON.EffectFallbacks();
  56181. if (useInstances) {
  56182. defines.push("#define INSTANCES");
  56183. }
  56184. for (var index = 0; index < this._options.defines.length; index++) {
  56185. defines.push(this._options.defines[index]);
  56186. }
  56187. for (var index = 0; index < this._options.attributes.length; index++) {
  56188. attribs.push(this._options.attributes[index]);
  56189. }
  56190. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  56191. attribs.push(BABYLON.VertexBuffer.ColorKind);
  56192. defines.push("#define VERTEXCOLOR");
  56193. }
  56194. // Bones
  56195. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  56196. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56197. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56198. if (mesh.numBoneInfluencers > 4) {
  56199. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56200. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56201. }
  56202. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56203. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56204. fallbacks.addCPUSkinningFallback(0, mesh);
  56205. if (this._options.uniforms.indexOf("mBones") === -1) {
  56206. this._options.uniforms.push("mBones");
  56207. }
  56208. }
  56209. else {
  56210. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56211. }
  56212. // Textures
  56213. for (var name in this._textures) {
  56214. if (!this._textures[name].isReady()) {
  56215. return false;
  56216. }
  56217. }
  56218. // Alpha test
  56219. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  56220. defines.push("#define ALPHATEST");
  56221. }
  56222. var previousEffect = this._effect;
  56223. var join = defines.join("\n");
  56224. this._effect = engine.createEffect(this._shaderPath, {
  56225. attributes: attribs,
  56226. uniformsNames: this._options.uniforms,
  56227. uniformBuffersNames: this._options.uniformBuffers,
  56228. samplers: this._options.samplers,
  56229. defines: join,
  56230. fallbacks: fallbacks,
  56231. onCompiled: this.onCompiled,
  56232. onError: this.onError
  56233. }, engine);
  56234. if (!this._effect.isReady()) {
  56235. return false;
  56236. }
  56237. if (previousEffect !== this._effect) {
  56238. scene.resetCachedMaterial();
  56239. }
  56240. this._renderId = scene.getRenderId();
  56241. return true;
  56242. };
  56243. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  56244. var scene = this.getScene();
  56245. if (!this._effect) {
  56246. return;
  56247. }
  56248. if (this._options.uniforms.indexOf("world") !== -1) {
  56249. this._effect.setMatrix("world", world);
  56250. }
  56251. if (this._options.uniforms.indexOf("worldView") !== -1) {
  56252. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  56253. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  56254. }
  56255. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  56256. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  56257. }
  56258. };
  56259. ShaderMaterial.prototype.bind = function (world, mesh) {
  56260. // Std values
  56261. this.bindOnlyWorldMatrix(world);
  56262. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  56263. if (this._options.uniforms.indexOf("view") !== -1) {
  56264. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  56265. }
  56266. if (this._options.uniforms.indexOf("projection") !== -1) {
  56267. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  56268. }
  56269. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  56270. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  56271. }
  56272. // Bones
  56273. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  56274. var name;
  56275. // Texture
  56276. for (name in this._textures) {
  56277. this._effect.setTexture(name, this._textures[name]);
  56278. }
  56279. // Texture arrays
  56280. for (name in this._textureArrays) {
  56281. this._effect.setTextureArray(name, this._textureArrays[name]);
  56282. }
  56283. // Int
  56284. for (name in this._ints) {
  56285. this._effect.setInt(name, this._ints[name]);
  56286. }
  56287. // Float
  56288. for (name in this._floats) {
  56289. this._effect.setFloat(name, this._floats[name]);
  56290. }
  56291. // Floats
  56292. for (name in this._floatsArrays) {
  56293. this._effect.setArray(name, this._floatsArrays[name]);
  56294. }
  56295. // Color3
  56296. for (name in this._colors3) {
  56297. this._effect.setColor3(name, this._colors3[name]);
  56298. }
  56299. for (name in this._colors3Arrays) {
  56300. this._effect.setArray3(name, this._colors3Arrays[name]);
  56301. }
  56302. // Color4
  56303. for (name in this._colors4) {
  56304. var color = this._colors4[name];
  56305. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56306. }
  56307. // Vector2
  56308. for (name in this._vectors2) {
  56309. this._effect.setVector2(name, this._vectors2[name]);
  56310. }
  56311. // Vector3
  56312. for (name in this._vectors3) {
  56313. this._effect.setVector3(name, this._vectors3[name]);
  56314. }
  56315. // Vector4
  56316. for (name in this._vectors4) {
  56317. this._effect.setVector4(name, this._vectors4[name]);
  56318. }
  56319. // Matrix
  56320. for (name in this._matrices) {
  56321. this._effect.setMatrix(name, this._matrices[name]);
  56322. }
  56323. // Matrix 3x3
  56324. for (name in this._matrices3x3) {
  56325. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  56326. }
  56327. // Matrix 2x2
  56328. for (name in this._matrices2x2) {
  56329. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  56330. }
  56331. // Vector2Array
  56332. for (name in this._vectors2Arrays) {
  56333. this._effect.setArray2(name, this._vectors2Arrays[name]);
  56334. }
  56335. // Vector3Array
  56336. for (name in this._vectors3Arrays) {
  56337. this._effect.setArray3(name, this._vectors3Arrays[name]);
  56338. }
  56339. }
  56340. this._afterBind(mesh);
  56341. };
  56342. ShaderMaterial.prototype.getActiveTextures = function () {
  56343. var activeTextures = _super.prototype.getActiveTextures.call(this);
  56344. for (var name in this._textures) {
  56345. activeTextures.push(this._textures[name]);
  56346. }
  56347. for (var name in this._textureArrays) {
  56348. var array = this._textureArrays[name];
  56349. for (var index = 0; index < array.length; index++) {
  56350. activeTextures.push(array[index]);
  56351. }
  56352. }
  56353. return activeTextures;
  56354. };
  56355. ShaderMaterial.prototype.hasTexture = function (texture) {
  56356. if (_super.prototype.hasTexture.call(this, texture)) {
  56357. return true;
  56358. }
  56359. for (var name in this._textures) {
  56360. if (this._textures[name] === texture) {
  56361. return true;
  56362. }
  56363. }
  56364. for (var name in this._textureArrays) {
  56365. var array = this._textureArrays[name];
  56366. for (var index = 0; index < array.length; index++) {
  56367. if (array[index] === texture) {
  56368. return true;
  56369. }
  56370. }
  56371. }
  56372. return false;
  56373. };
  56374. ShaderMaterial.prototype.clone = function (name) {
  56375. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  56376. return newShaderMaterial;
  56377. };
  56378. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56379. if (forceDisposeTextures) {
  56380. var name;
  56381. for (name in this._textures) {
  56382. this._textures[name].dispose();
  56383. }
  56384. for (name in this._textureArrays) {
  56385. var array = this._textureArrays[name];
  56386. for (var index = 0; index < array.length; index++) {
  56387. array[index].dispose();
  56388. }
  56389. }
  56390. }
  56391. this._textures = {};
  56392. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56393. };
  56394. ShaderMaterial.prototype.serialize = function () {
  56395. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  56396. serializationObject.customType = "BABYLON.ShaderMaterial";
  56397. serializationObject.options = this._options;
  56398. serializationObject.shaderPath = this._shaderPath;
  56399. var name;
  56400. // Texture
  56401. serializationObject.textures = {};
  56402. for (name in this._textures) {
  56403. serializationObject.textures[name] = this._textures[name].serialize();
  56404. }
  56405. // Texture arrays
  56406. serializationObject.textureArrays = {};
  56407. for (name in this._textureArrays) {
  56408. serializationObject.textureArrays[name] = [];
  56409. var array = this._textureArrays[name];
  56410. for (var index = 0; index < array.length; index++) {
  56411. serializationObject.textureArrays[name].push(array[index].serialize());
  56412. }
  56413. }
  56414. // Float
  56415. serializationObject.floats = {};
  56416. for (name in this._floats) {
  56417. serializationObject.floats[name] = this._floats[name];
  56418. }
  56419. // Float s
  56420. serializationObject.FloatArrays = {};
  56421. for (name in this._floatsArrays) {
  56422. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  56423. }
  56424. // Color3
  56425. serializationObject.colors3 = {};
  56426. for (name in this._colors3) {
  56427. serializationObject.colors3[name] = this._colors3[name].asArray();
  56428. }
  56429. // Color3 array
  56430. serializationObject.colors3Arrays = {};
  56431. for (name in this._colors3Arrays) {
  56432. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  56433. }
  56434. // Color4
  56435. serializationObject.colors4 = {};
  56436. for (name in this._colors4) {
  56437. serializationObject.colors4[name] = this._colors4[name].asArray();
  56438. }
  56439. // Vector2
  56440. serializationObject.vectors2 = {};
  56441. for (name in this._vectors2) {
  56442. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  56443. }
  56444. // Vector3
  56445. serializationObject.vectors3 = {};
  56446. for (name in this._vectors3) {
  56447. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  56448. }
  56449. // Vector4
  56450. serializationObject.vectors4 = {};
  56451. for (name in this._vectors4) {
  56452. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  56453. }
  56454. // Matrix
  56455. serializationObject.matrices = {};
  56456. for (name in this._matrices) {
  56457. serializationObject.matrices[name] = this._matrices[name].asArray();
  56458. }
  56459. // Matrix 3x3
  56460. serializationObject.matrices3x3 = {};
  56461. for (name in this._matrices3x3) {
  56462. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  56463. }
  56464. // Matrix 2x2
  56465. serializationObject.matrices2x2 = {};
  56466. for (name in this._matrices2x2) {
  56467. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  56468. }
  56469. // Vector2Array
  56470. serializationObject.vectors2Arrays = {};
  56471. for (name in this._vectors2Arrays) {
  56472. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  56473. }
  56474. // Vector3Array
  56475. serializationObject.vectors3Arrays = {};
  56476. for (name in this._vectors3Arrays) {
  56477. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  56478. }
  56479. return serializationObject;
  56480. };
  56481. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  56482. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  56483. var name;
  56484. // Texture
  56485. for (name in source.textures) {
  56486. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  56487. }
  56488. // Texture arrays
  56489. for (name in source.textureArrays) {
  56490. var array = source.textureArrays[name];
  56491. var textureArray = new Array();
  56492. for (var index = 0; index < array.length; index++) {
  56493. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  56494. }
  56495. material.setTextureArray(name, textureArray);
  56496. }
  56497. // Float
  56498. for (name in source.floats) {
  56499. material.setFloat(name, source.floats[name]);
  56500. }
  56501. // Float s
  56502. for (name in source.floatsArrays) {
  56503. material.setFloats(name, source.floatsArrays[name]);
  56504. }
  56505. // Color3
  56506. for (name in source.colors3) {
  56507. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  56508. }
  56509. // Color3 arrays
  56510. for (name in source.colors3Arrays) {
  56511. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  56512. if (i % 3 === 0) {
  56513. arr.push([num]);
  56514. }
  56515. else {
  56516. arr[arr.length - 1].push(num);
  56517. }
  56518. return arr;
  56519. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  56520. material.setColor3Array(name, colors);
  56521. }
  56522. // Color4
  56523. for (name in source.colors4) {
  56524. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  56525. }
  56526. // Vector2
  56527. for (name in source.vectors2) {
  56528. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  56529. }
  56530. // Vector3
  56531. for (name in source.vectors3) {
  56532. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  56533. }
  56534. // Vector4
  56535. for (name in source.vectors4) {
  56536. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  56537. }
  56538. // Matrix
  56539. for (name in source.matrices) {
  56540. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  56541. }
  56542. // Matrix 3x3
  56543. for (name in source.matrices3x3) {
  56544. material.setMatrix3x3(name, source.matrices3x3[name]);
  56545. }
  56546. // Matrix 2x2
  56547. for (name in source.matrices2x2) {
  56548. material.setMatrix2x2(name, source.matrices2x2[name]);
  56549. }
  56550. // Vector2Array
  56551. for (name in source.vectors2Arrays) {
  56552. material.setArray2(name, source.vectors2Arrays[name]);
  56553. }
  56554. // Vector3Array
  56555. for (name in source.vectors3Arrays) {
  56556. material.setArray3(name, source.vectors3Arrays[name]);
  56557. }
  56558. return material;
  56559. };
  56560. return ShaderMaterial;
  56561. }(BABYLON.Material));
  56562. BABYLON.ShaderMaterial = ShaderMaterial;
  56563. })(BABYLON || (BABYLON = {}));
  56564. //# sourceMappingURL=babylon.shaderMaterial.js.map
  56565. "use strict";
  56566. var BABYLON;
  56567. (function (BABYLON) {
  56568. var GroundMesh = /** @class */ (function (_super) {
  56569. __extends(GroundMesh, _super);
  56570. function GroundMesh(name, scene) {
  56571. var _this = _super.call(this, name, scene) || this;
  56572. _this.generateOctree = false;
  56573. return _this;
  56574. }
  56575. GroundMesh.prototype.getClassName = function () {
  56576. return "GroundMesh";
  56577. };
  56578. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  56579. get: function () {
  56580. return Math.min(this._subdivisionsX, this._subdivisionsY);
  56581. },
  56582. enumerable: true,
  56583. configurable: true
  56584. });
  56585. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  56586. get: function () {
  56587. return this._subdivisionsX;
  56588. },
  56589. enumerable: true,
  56590. configurable: true
  56591. });
  56592. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  56593. get: function () {
  56594. return this._subdivisionsY;
  56595. },
  56596. enumerable: true,
  56597. configurable: true
  56598. });
  56599. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  56600. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  56601. this._subdivisionsX = chunksCount;
  56602. this._subdivisionsY = chunksCount;
  56603. this.subdivide(chunksCount);
  56604. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  56605. };
  56606. /**
  56607. * Returns a height (y) value in the Worl system :
  56608. * the ground altitude at the coordinates (x, z) expressed in the World system.
  56609. * Returns the ground y position if (x, z) are outside the ground surface.
  56610. */
  56611. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  56612. var world = this.getWorldMatrix();
  56613. var invMat = BABYLON.Tmp.Matrix[5];
  56614. world.invertToRef(invMat);
  56615. var tmpVect = BABYLON.Tmp.Vector3[8];
  56616. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  56617. x = tmpVect.x;
  56618. z = tmpVect.z;
  56619. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  56620. return this.position.y;
  56621. }
  56622. if (!this._heightQuads || this._heightQuads.length == 0) {
  56623. this._initHeightQuads();
  56624. this._computeHeightQuads();
  56625. }
  56626. var facet = this._getFacetAt(x, z);
  56627. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  56628. // return y in the World system
  56629. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  56630. return tmpVect.y;
  56631. };
  56632. /**
  56633. * Returns a normalized vector (Vector3) orthogonal to the ground
  56634. * at the ground coordinates (x, z) expressed in the World system.
  56635. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  56636. */
  56637. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  56638. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  56639. this.getNormalAtCoordinatesToRef(x, z, normal);
  56640. return normal;
  56641. };
  56642. /**
  56643. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  56644. * at the ground coordinates (x, z) expressed in the World system.
  56645. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  56646. * Returns the GroundMesh.
  56647. */
  56648. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  56649. var world = this.getWorldMatrix();
  56650. var tmpMat = BABYLON.Tmp.Matrix[5];
  56651. world.invertToRef(tmpMat);
  56652. var tmpVect = BABYLON.Tmp.Vector3[8];
  56653. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  56654. x = tmpVect.x;
  56655. z = tmpVect.z;
  56656. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  56657. return this;
  56658. }
  56659. if (!this._heightQuads || this._heightQuads.length == 0) {
  56660. this._initHeightQuads();
  56661. this._computeHeightQuads();
  56662. }
  56663. var facet = this._getFacetAt(x, z);
  56664. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  56665. return this;
  56666. };
  56667. /**
  56668. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  56669. * if the ground has been updated.
  56670. * This can be used in the render loop.
  56671. * Returns the GroundMesh.
  56672. */
  56673. GroundMesh.prototype.updateCoordinateHeights = function () {
  56674. if (!this._heightQuads || this._heightQuads.length == 0) {
  56675. this._initHeightQuads();
  56676. }
  56677. this._computeHeightQuads();
  56678. return this;
  56679. };
  56680. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  56681. GroundMesh.prototype._getFacetAt = function (x, z) {
  56682. // retrieve col and row from x, z coordinates in the ground local system
  56683. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  56684. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  56685. var quad = this._heightQuads[row * this._subdivisionsX + col];
  56686. var facet;
  56687. if (z < quad.slope.x * x + quad.slope.y) {
  56688. facet = quad.facet1;
  56689. }
  56690. else {
  56691. facet = quad.facet2;
  56692. }
  56693. return facet;
  56694. };
  56695. // Creates and populates the heightMap array with "facet" elements :
  56696. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  56697. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56698. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56699. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56700. // Returns the GroundMesh.
  56701. GroundMesh.prototype._initHeightQuads = function () {
  56702. var subdivisionsX = this._subdivisionsX;
  56703. var subdivisionsY = this._subdivisionsY;
  56704. this._heightQuads = new Array();
  56705. for (var row = 0; row < subdivisionsY; row++) {
  56706. for (var col = 0; col < subdivisionsX; col++) {
  56707. 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) };
  56708. this._heightQuads[row * subdivisionsX + col] = quad;
  56709. }
  56710. }
  56711. return this;
  56712. };
  56713. // Compute each quad element values and update the the heightMap array :
  56714. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  56715. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  56716. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  56717. // Returns the GroundMesh.
  56718. GroundMesh.prototype._computeHeightQuads = function () {
  56719. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56720. if (!positions) {
  56721. return this;
  56722. }
  56723. var v1 = BABYLON.Tmp.Vector3[3];
  56724. var v2 = BABYLON.Tmp.Vector3[2];
  56725. var v3 = BABYLON.Tmp.Vector3[1];
  56726. var v4 = BABYLON.Tmp.Vector3[0];
  56727. var v1v2 = BABYLON.Tmp.Vector3[4];
  56728. var v1v3 = BABYLON.Tmp.Vector3[5];
  56729. var v1v4 = BABYLON.Tmp.Vector3[6];
  56730. var norm1 = BABYLON.Tmp.Vector3[7];
  56731. var norm2 = BABYLON.Tmp.Vector3[8];
  56732. var i = 0;
  56733. var j = 0;
  56734. var k = 0;
  56735. var cd = 0; // 2D slope coefficient : z = cd * x + h
  56736. var h = 0;
  56737. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  56738. var d2 = 0;
  56739. var subdivisionsX = this._subdivisionsX;
  56740. var subdivisionsY = this._subdivisionsY;
  56741. for (var row = 0; row < subdivisionsY; row++) {
  56742. for (var col = 0; col < subdivisionsX; col++) {
  56743. i = col * 3;
  56744. j = row * (subdivisionsX + 1) * 3;
  56745. k = (row + 1) * (subdivisionsX + 1) * 3;
  56746. v1.x = positions[j + i];
  56747. v1.y = positions[j + i + 1];
  56748. v1.z = positions[j + i + 2];
  56749. v2.x = positions[j + i + 3];
  56750. v2.y = positions[j + i + 4];
  56751. v2.z = positions[j + i + 5];
  56752. v3.x = positions[k + i];
  56753. v3.y = positions[k + i + 1];
  56754. v3.z = positions[k + i + 2];
  56755. v4.x = positions[k + i + 3];
  56756. v4.y = positions[k + i + 4];
  56757. v4.z = positions[k + i + 5];
  56758. // 2D slope V1V4
  56759. cd = (v4.z - v1.z) / (v4.x - v1.x);
  56760. h = v1.z - cd * v1.x; // v1 belongs to the slope
  56761. // facet equations :
  56762. // we compute each facet normal vector
  56763. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  56764. // we compute the value d by applying the equation to v1 which belongs to the plane
  56765. // then we store the facet equation in a Vector4
  56766. v2.subtractToRef(v1, v1v2);
  56767. v3.subtractToRef(v1, v1v3);
  56768. v4.subtractToRef(v1, v1v4);
  56769. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  56770. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  56771. norm1.normalize();
  56772. norm2.normalize();
  56773. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  56774. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  56775. var quad = this._heightQuads[row * subdivisionsX + col];
  56776. quad.slope.copyFromFloats(cd, h);
  56777. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  56778. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  56779. }
  56780. }
  56781. return this;
  56782. };
  56783. GroundMesh.prototype.serialize = function (serializationObject) {
  56784. _super.prototype.serialize.call(this, serializationObject);
  56785. serializationObject.subdivisionsX = this._subdivisionsX;
  56786. serializationObject.subdivisionsY = this._subdivisionsY;
  56787. serializationObject.minX = this._minX;
  56788. serializationObject.maxX = this._maxX;
  56789. serializationObject.minZ = this._minZ;
  56790. serializationObject.maxZ = this._maxZ;
  56791. serializationObject.width = this._width;
  56792. serializationObject.height = this._height;
  56793. };
  56794. GroundMesh.Parse = function (parsedMesh, scene) {
  56795. var result = new GroundMesh(parsedMesh.name, scene);
  56796. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56797. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56798. result._minX = parsedMesh.minX;
  56799. result._maxX = parsedMesh.maxX;
  56800. result._minZ = parsedMesh.minZ;
  56801. result._maxZ = parsedMesh.maxZ;
  56802. result._width = parsedMesh.width;
  56803. result._height = parsedMesh.height;
  56804. return result;
  56805. };
  56806. return GroundMesh;
  56807. }(BABYLON.Mesh));
  56808. BABYLON.GroundMesh = GroundMesh;
  56809. })(BABYLON || (BABYLON = {}));
  56810. //# sourceMappingURL=babylon.groundMesh.js.map
  56811. "use strict";
  56812. var BABYLON;
  56813. (function (BABYLON) {
  56814. /**
  56815. * Creates an instance based on a source mesh.
  56816. */
  56817. var InstancedMesh = /** @class */ (function (_super) {
  56818. __extends(InstancedMesh, _super);
  56819. function InstancedMesh(name, source) {
  56820. var _this = _super.call(this, name, source.getScene()) || this;
  56821. source.instances.push(_this);
  56822. _this._sourceMesh = source;
  56823. _this.position.copyFrom(source.position);
  56824. _this.rotation.copyFrom(source.rotation);
  56825. _this.scaling.copyFrom(source.scaling);
  56826. if (source.rotationQuaternion) {
  56827. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56828. }
  56829. _this.infiniteDistance = source.infiniteDistance;
  56830. _this.setPivotMatrix(source.getPivotMatrix());
  56831. _this.refreshBoundingInfo();
  56832. _this._syncSubMeshes();
  56833. return _this;
  56834. }
  56835. /**
  56836. * Returns the string "InstancedMesh".
  56837. */
  56838. InstancedMesh.prototype.getClassName = function () {
  56839. return "InstancedMesh";
  56840. };
  56841. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56842. // Methods
  56843. get: function () {
  56844. return this._sourceMesh.receiveShadows;
  56845. },
  56846. enumerable: true,
  56847. configurable: true
  56848. });
  56849. Object.defineProperty(InstancedMesh.prototype, "material", {
  56850. get: function () {
  56851. return this._sourceMesh.material;
  56852. },
  56853. enumerable: true,
  56854. configurable: true
  56855. });
  56856. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56857. get: function () {
  56858. return this._sourceMesh.visibility;
  56859. },
  56860. enumerable: true,
  56861. configurable: true
  56862. });
  56863. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56864. get: function () {
  56865. return this._sourceMesh.skeleton;
  56866. },
  56867. enumerable: true,
  56868. configurable: true
  56869. });
  56870. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56871. get: function () {
  56872. return this._sourceMesh.renderingGroupId;
  56873. },
  56874. set: function (value) {
  56875. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56876. return;
  56877. }
  56878. //no-op with warning
  56879. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56880. },
  56881. enumerable: true,
  56882. configurable: true
  56883. });
  56884. /**
  56885. * Returns the total number of vertices (integer).
  56886. */
  56887. InstancedMesh.prototype.getTotalVertices = function () {
  56888. return this._sourceMesh.getTotalVertices();
  56889. };
  56890. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56891. get: function () {
  56892. return this._sourceMesh;
  56893. },
  56894. enumerable: true,
  56895. configurable: true
  56896. });
  56897. /**
  56898. * Is this node ready to be used/rendered
  56899. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56900. * @return {boolean} is it ready
  56901. */
  56902. InstancedMesh.prototype.isReady = function (completeCheck) {
  56903. if (completeCheck === void 0) { completeCheck = false; }
  56904. return this._sourceMesh.isReady(completeCheck, true);
  56905. };
  56906. /**
  56907. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56908. */
  56909. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56910. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56911. };
  56912. /**
  56913. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56914. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56915. * The `data` are either a numeric array either a Float32Array.
  56916. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56917. * 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).
  56918. * Note that a new underlying VertexBuffer object is created each call.
  56919. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56920. *
  56921. * Possible `kind` values :
  56922. * - BABYLON.VertexBuffer.PositionKind
  56923. * - BABYLON.VertexBuffer.UVKind
  56924. * - BABYLON.VertexBuffer.UV2Kind
  56925. * - BABYLON.VertexBuffer.UV3Kind
  56926. * - BABYLON.VertexBuffer.UV4Kind
  56927. * - BABYLON.VertexBuffer.UV5Kind
  56928. * - BABYLON.VertexBuffer.UV6Kind
  56929. * - BABYLON.VertexBuffer.ColorKind
  56930. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56931. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56932. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56933. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56934. *
  56935. * Returns the Mesh.
  56936. */
  56937. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56938. if (this.sourceMesh) {
  56939. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56940. }
  56941. return this.sourceMesh;
  56942. };
  56943. /**
  56944. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56945. * If the mesh has no geometry, it is simply returned as it is.
  56946. * The `data` are either a numeric array either a Float32Array.
  56947. * No new underlying VertexBuffer object is created.
  56948. * 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.
  56949. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56950. *
  56951. * Possible `kind` values :
  56952. * - BABYLON.VertexBuffer.PositionKind
  56953. * - BABYLON.VertexBuffer.UVKind
  56954. * - BABYLON.VertexBuffer.UV2Kind
  56955. * - BABYLON.VertexBuffer.UV3Kind
  56956. * - BABYLON.VertexBuffer.UV4Kind
  56957. * - BABYLON.VertexBuffer.UV5Kind
  56958. * - BABYLON.VertexBuffer.UV6Kind
  56959. * - BABYLON.VertexBuffer.ColorKind
  56960. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56961. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56962. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56963. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56964. *
  56965. * Returns the Mesh.
  56966. */
  56967. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56968. if (this.sourceMesh) {
  56969. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56970. }
  56971. return this.sourceMesh;
  56972. };
  56973. /**
  56974. * Sets the mesh indices.
  56975. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56976. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56977. * This method creates a new index buffer each call.
  56978. * Returns the Mesh.
  56979. */
  56980. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56981. if (totalVertices === void 0) { totalVertices = null; }
  56982. if (this.sourceMesh) {
  56983. this.sourceMesh.setIndices(indices, totalVertices);
  56984. }
  56985. return this.sourceMesh;
  56986. };
  56987. /**
  56988. * Boolean : True if the mesh owns the requested kind of data.
  56989. */
  56990. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56991. return this._sourceMesh.isVerticesDataPresent(kind);
  56992. };
  56993. /**
  56994. * Returns an array of indices (IndicesArray).
  56995. */
  56996. InstancedMesh.prototype.getIndices = function () {
  56997. return this._sourceMesh.getIndices();
  56998. };
  56999. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  57000. get: function () {
  57001. return this._sourceMesh._positions;
  57002. },
  57003. enumerable: true,
  57004. configurable: true
  57005. });
  57006. /**
  57007. * Sets a new updated BoundingInfo to the mesh.
  57008. * Returns the mesh.
  57009. */
  57010. InstancedMesh.prototype.refreshBoundingInfo = function () {
  57011. var meshBB = this._sourceMesh.getBoundingInfo();
  57012. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  57013. this._updateBoundingInfo();
  57014. return this;
  57015. };
  57016. InstancedMesh.prototype._preActivate = function () {
  57017. if (this._currentLOD) {
  57018. this._currentLOD._preActivate();
  57019. }
  57020. return this;
  57021. };
  57022. InstancedMesh.prototype._activate = function (renderId) {
  57023. if (this._currentLOD) {
  57024. this._currentLOD._registerInstanceForRenderId(this, renderId);
  57025. }
  57026. return this;
  57027. };
  57028. /**
  57029. * Returns the current associated LOD AbstractMesh.
  57030. */
  57031. InstancedMesh.prototype.getLOD = function (camera) {
  57032. if (!camera) {
  57033. return this;
  57034. }
  57035. var boundingInfo = this.getBoundingInfo();
  57036. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  57037. if (this._currentLOD === this.sourceMesh) {
  57038. return this;
  57039. }
  57040. return this._currentLOD;
  57041. };
  57042. InstancedMesh.prototype._syncSubMeshes = function () {
  57043. this.releaseSubMeshes();
  57044. if (this._sourceMesh.subMeshes) {
  57045. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  57046. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  57047. }
  57048. }
  57049. return this;
  57050. };
  57051. InstancedMesh.prototype._generatePointsArray = function () {
  57052. return this._sourceMesh._generatePointsArray();
  57053. };
  57054. /**
  57055. * Creates a new InstancedMesh from the current mesh.
  57056. * - name (string) : the cloned mesh name
  57057. * - newParent (optional Node) : the optional Node to parent the clone to.
  57058. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  57059. *
  57060. * Returns the clone.
  57061. */
  57062. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57063. var result = this._sourceMesh.createInstance(name);
  57064. // Deep copy
  57065. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  57066. // Bounding info
  57067. this.refreshBoundingInfo();
  57068. // Parent
  57069. if (newParent) {
  57070. result.parent = newParent;
  57071. }
  57072. if (!doNotCloneChildren) {
  57073. // Children
  57074. for (var index = 0; index < this.getScene().meshes.length; index++) {
  57075. var mesh = this.getScene().meshes[index];
  57076. if (mesh.parent === this) {
  57077. mesh.clone(mesh.name, result);
  57078. }
  57079. }
  57080. }
  57081. result.computeWorldMatrix(true);
  57082. return result;
  57083. };
  57084. /**
  57085. * Disposes the InstancedMesh.
  57086. * Returns nothing.
  57087. */
  57088. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  57089. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  57090. // Remove from mesh
  57091. var index = this._sourceMesh.instances.indexOf(this);
  57092. this._sourceMesh.instances.splice(index, 1);
  57093. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  57094. };
  57095. return InstancedMesh;
  57096. }(BABYLON.AbstractMesh));
  57097. BABYLON.InstancedMesh = InstancedMesh;
  57098. })(BABYLON || (BABYLON = {}));
  57099. //# sourceMappingURL=babylon.instancedMesh.js.map
  57100. "use strict";
  57101. var BABYLON;
  57102. (function (BABYLON) {
  57103. var LinesMesh = /** @class */ (function (_super) {
  57104. __extends(LinesMesh, _super);
  57105. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  57106. if (scene === void 0) { scene = null; }
  57107. if (parent === void 0) { parent = null; }
  57108. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  57109. _this.useVertexColor = useVertexColor;
  57110. _this.useVertexAlpha = useVertexAlpha;
  57111. _this.color = new BABYLON.Color3(1, 1, 1);
  57112. _this.alpha = 1;
  57113. if (source) {
  57114. _this.color = source.color.clone();
  57115. _this.alpha = source.alpha;
  57116. _this.useVertexColor = source.useVertexColor;
  57117. _this.useVertexAlpha = source.useVertexAlpha;
  57118. }
  57119. _this._intersectionThreshold = 0.1;
  57120. var defines = [];
  57121. var options = {
  57122. attributes: [BABYLON.VertexBuffer.PositionKind],
  57123. uniforms: ["world", "viewProjection"],
  57124. needAlphaBlending: true,
  57125. defines: defines
  57126. };
  57127. if (useVertexAlpha === false) {
  57128. options.needAlphaBlending = false;
  57129. }
  57130. if (!useVertexColor) {
  57131. options.uniforms.push("color");
  57132. }
  57133. else {
  57134. options.defines.push("#define VERTEXCOLOR");
  57135. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  57136. }
  57137. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  57138. return _this;
  57139. }
  57140. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  57141. /**
  57142. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57143. * This margin is expressed in world space coordinates, so its value may vary.
  57144. * Default value is 0.1
  57145. * @returns the intersection Threshold value.
  57146. */
  57147. get: function () {
  57148. return this._intersectionThreshold;
  57149. },
  57150. /**
  57151. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  57152. * This margin is expressed in world space coordinates, so its value may vary.
  57153. * @param value the new threshold to apply
  57154. */
  57155. set: function (value) {
  57156. if (this._intersectionThreshold === value) {
  57157. return;
  57158. }
  57159. this._intersectionThreshold = value;
  57160. if (this.geometry) {
  57161. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  57162. }
  57163. },
  57164. enumerable: true,
  57165. configurable: true
  57166. });
  57167. /**
  57168. * Returns the string "LineMesh"
  57169. */
  57170. LinesMesh.prototype.getClassName = function () {
  57171. return "LinesMesh";
  57172. };
  57173. Object.defineProperty(LinesMesh.prototype, "material", {
  57174. get: function () {
  57175. return this._colorShader;
  57176. },
  57177. set: function (value) {
  57178. // Do nothing
  57179. },
  57180. enumerable: true,
  57181. configurable: true
  57182. });
  57183. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  57184. get: function () {
  57185. return false;
  57186. },
  57187. enumerable: true,
  57188. configurable: true
  57189. });
  57190. LinesMesh.prototype.createInstance = function (name) {
  57191. throw new Error("LinesMeshes do not support createInstance.");
  57192. };
  57193. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  57194. if (!this._geometry) {
  57195. return this;
  57196. }
  57197. // VBOs
  57198. this._geometry._bind(this._colorShader.getEffect());
  57199. // Color
  57200. if (!this.useVertexColor) {
  57201. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  57202. }
  57203. return this;
  57204. };
  57205. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  57206. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  57207. return this;
  57208. }
  57209. var engine = this.getScene().getEngine();
  57210. // Draw order
  57211. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  57212. return this;
  57213. };
  57214. LinesMesh.prototype.dispose = function (doNotRecurse) {
  57215. this._colorShader.dispose();
  57216. _super.prototype.dispose.call(this, doNotRecurse);
  57217. };
  57218. /**
  57219. * Returns a new LineMesh object cloned from the current one.
  57220. */
  57221. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  57222. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  57223. };
  57224. return LinesMesh;
  57225. }(BABYLON.Mesh));
  57226. BABYLON.LinesMesh = LinesMesh;
  57227. })(BABYLON || (BABYLON = {}));
  57228. //# sourceMappingURL=babylon.linesMesh.js.map
  57229. "use strict";
  57230. var BABYLON;
  57231. (function (BABYLON) {
  57232. var MeshBuilder = /** @class */ (function () {
  57233. function MeshBuilder() {
  57234. }
  57235. MeshBuilder.updateSideOrientation = function (orientation) {
  57236. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  57237. return BABYLON.Mesh.DOUBLESIDE;
  57238. }
  57239. if (orientation === undefined || orientation === null) {
  57240. return BABYLON.Mesh.FRONTSIDE;
  57241. }
  57242. return orientation;
  57243. };
  57244. /**
  57245. * Creates a box mesh.
  57246. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  57247. * The parameter `size` sets the size (float) of each box side (default 1).
  57248. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  57249. * 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).
  57250. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57252. * 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).
  57253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57255. */
  57256. MeshBuilder.CreateBox = function (name, options, scene) {
  57257. if (scene === void 0) { scene = null; }
  57258. var box = new BABYLON.Mesh(name, scene);
  57259. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57260. box._originalBuilderSideOrientation = options.sideOrientation;
  57261. var vertexData = BABYLON.VertexData.CreateBox(options);
  57262. vertexData.applyToMesh(box, options.updatable);
  57263. return box;
  57264. };
  57265. /**
  57266. * Creates a sphere mesh.
  57267. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  57268. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  57269. * 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`).
  57270. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  57271. * 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
  57272. * 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).
  57273. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57274. * 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).
  57275. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57276. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57277. */
  57278. MeshBuilder.CreateSphere = function (name, options, scene) {
  57279. var sphere = new BABYLON.Mesh(name, scene);
  57280. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57281. sphere._originalBuilderSideOrientation = options.sideOrientation;
  57282. var vertexData = BABYLON.VertexData.CreateSphere(options);
  57283. vertexData.applyToMesh(sphere, options.updatable);
  57284. return sphere;
  57285. };
  57286. /**
  57287. * Creates a plane polygonal mesh. By default, this is a disc.
  57288. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  57289. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  57290. * 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.
  57291. * 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
  57292. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57293. * 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).
  57294. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57296. */
  57297. MeshBuilder.CreateDisc = function (name, options, scene) {
  57298. if (scene === void 0) { scene = null; }
  57299. var disc = new BABYLON.Mesh(name, scene);
  57300. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57301. disc._originalBuilderSideOrientation = options.sideOrientation;
  57302. var vertexData = BABYLON.VertexData.CreateDisc(options);
  57303. vertexData.applyToMesh(disc, options.updatable);
  57304. return disc;
  57305. };
  57306. /**
  57307. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  57308. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  57309. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  57310. * 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`).
  57311. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  57312. * 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.
  57313. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57314. * 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).
  57315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57317. */
  57318. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  57319. var sphere = new BABYLON.Mesh(name, scene);
  57320. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57321. sphere._originalBuilderSideOrientation = options.sideOrientation;
  57322. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  57323. vertexData.applyToMesh(sphere, options.updatable);
  57324. return sphere;
  57325. };
  57326. ;
  57327. /**
  57328. * Creates a ribbon mesh.
  57329. * 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.
  57330. *
  57331. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  57332. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  57333. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  57334. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  57335. * 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.
  57336. * 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.
  57337. * 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
  57338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57339. * 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).
  57340. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57341. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57342. * 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.
  57343. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  57344. * 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
  57345. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  57346. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  57347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57348. */
  57349. MeshBuilder.CreateRibbon = function (name, options, scene) {
  57350. if (scene === void 0) { scene = null; }
  57351. var pathArray = options.pathArray;
  57352. var closeArray = options.closeArray;
  57353. var closePath = options.closePath;
  57354. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57355. var instance = options.instance;
  57356. var updatable = options.updatable;
  57357. if (instance) {
  57358. // positionFunction : ribbon case
  57359. // only pathArray and sideOrientation parameters are taken into account for positions update
  57360. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  57361. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  57362. var positionFunction = function (positions) {
  57363. var minlg = pathArray[0].length;
  57364. var i = 0;
  57365. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  57366. for (var si = 1; si <= ns; si++) {
  57367. for (var p = 0; p < pathArray.length; p++) {
  57368. var path = pathArray[p];
  57369. var l = path.length;
  57370. minlg = (minlg < l) ? minlg : l;
  57371. var j = 0;
  57372. while (j < minlg) {
  57373. positions[i] = path[j].x;
  57374. positions[i + 1] = path[j].y;
  57375. positions[i + 2] = path[j].z;
  57376. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  57377. BABYLON.Tmp.Vector3[0].x = path[j].x;
  57378. }
  57379. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  57380. BABYLON.Tmp.Vector3[1].x = path[j].x;
  57381. }
  57382. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  57383. BABYLON.Tmp.Vector3[0].y = path[j].y;
  57384. }
  57385. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  57386. BABYLON.Tmp.Vector3[1].y = path[j].y;
  57387. }
  57388. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  57389. BABYLON.Tmp.Vector3[0].z = path[j].z;
  57390. }
  57391. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  57392. BABYLON.Tmp.Vector3[1].z = path[j].z;
  57393. }
  57394. j++;
  57395. i += 3;
  57396. }
  57397. if (instance._closePath) {
  57398. positions[i] = path[0].x;
  57399. positions[i + 1] = path[0].y;
  57400. positions[i + 2] = path[0].z;
  57401. i += 3;
  57402. }
  57403. }
  57404. }
  57405. };
  57406. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57407. positionFunction(positions);
  57408. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  57409. instance._boundingInfo.update(instance._worldMatrix);
  57410. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  57411. if (options.colors) {
  57412. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57413. for (var c = 0; c < options.colors.length; c++) {
  57414. colors[c * 4] = options.colors[c].r;
  57415. colors[c * 4 + 1] = options.colors[c].g;
  57416. colors[c * 4 + 2] = options.colors[c].b;
  57417. colors[c * 4 + 3] = options.colors[c].a;
  57418. }
  57419. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  57420. }
  57421. if (options.uvs) {
  57422. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57423. for (var i = 0; i < options.uvs.length; i++) {
  57424. uvs[i * 2] = options.uvs[i].x;
  57425. uvs[i * 2 + 1] = options.uvs[i].y;
  57426. }
  57427. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  57428. }
  57429. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  57430. var indices = instance.getIndices();
  57431. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57432. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  57433. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  57434. if (instance._closePath) {
  57435. var indexFirst = 0;
  57436. var indexLast = 0;
  57437. for (var p = 0; p < pathArray.length; p++) {
  57438. indexFirst = instance._idx[p] * 3;
  57439. if (p + 1 < pathArray.length) {
  57440. indexLast = (instance._idx[p + 1] - 1) * 3;
  57441. }
  57442. else {
  57443. indexLast = normals.length - 3;
  57444. }
  57445. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  57446. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  57447. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  57448. normals[indexLast] = normals[indexFirst];
  57449. normals[indexLast + 1] = normals[indexFirst + 1];
  57450. normals[indexLast + 2] = normals[indexFirst + 2];
  57451. }
  57452. }
  57453. if (!(instance.areNormalsFrozen)) {
  57454. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  57455. }
  57456. }
  57457. return instance;
  57458. }
  57459. else {
  57460. var ribbon = new BABYLON.Mesh(name, scene);
  57461. ribbon._originalBuilderSideOrientation = sideOrientation;
  57462. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  57463. if (closePath) {
  57464. ribbon._idx = vertexData._idx;
  57465. }
  57466. ribbon._closePath = closePath;
  57467. ribbon._closeArray = closeArray;
  57468. vertexData.applyToMesh(ribbon, updatable);
  57469. return ribbon;
  57470. }
  57471. };
  57472. /**
  57473. * Creates a cylinder or a cone mesh.
  57474. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  57475. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  57476. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  57477. * 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.
  57478. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  57479. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  57480. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  57481. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  57482. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  57483. * 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).
  57484. * 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
  57485. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  57486. * 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
  57487. * 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.
  57488. * If `enclose` is false, a ring surface is one element.
  57489. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  57490. * 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
  57491. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57492. * 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).
  57493. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57494. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57495. */
  57496. MeshBuilder.CreateCylinder = function (name, options, scene) {
  57497. var cylinder = new BABYLON.Mesh(name, scene);
  57498. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57499. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  57500. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  57501. vertexData.applyToMesh(cylinder, options.updatable);
  57502. return cylinder;
  57503. };
  57504. /**
  57505. * Creates a torus mesh.
  57506. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  57507. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  57508. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  57509. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  57510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57511. * 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).
  57512. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57514. */
  57515. MeshBuilder.CreateTorus = function (name, options, scene) {
  57516. var torus = new BABYLON.Mesh(name, scene);
  57517. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57518. torus._originalBuilderSideOrientation = options.sideOrientation;
  57519. var vertexData = BABYLON.VertexData.CreateTorus(options);
  57520. vertexData.applyToMesh(torus, options.updatable);
  57521. return torus;
  57522. };
  57523. /**
  57524. * Creates a torus knot mesh.
  57525. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  57526. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  57527. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  57528. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  57529. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  57530. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57531. * 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).
  57532. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57534. */
  57535. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  57536. var torusKnot = new BABYLON.Mesh(name, scene);
  57537. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57538. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  57539. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  57540. vertexData.applyToMesh(torusKnot, options.updatable);
  57541. return torusKnot;
  57542. };
  57543. /**
  57544. * Creates a line system mesh.
  57545. * A line system is a pool of many lines gathered in a single mesh.
  57546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  57547. * 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.
  57548. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  57549. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  57550. * 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
  57551. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  57552. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  57553. * 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
  57554. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  57555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57556. */
  57557. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  57558. var instance = options.instance;
  57559. var lines = options.lines;
  57560. var colors = options.colors;
  57561. if (instance) {
  57562. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57563. var vertexColor;
  57564. var lineColors;
  57565. if (colors) {
  57566. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57567. }
  57568. var i = 0;
  57569. var c = 0;
  57570. for (var l = 0; l < lines.length; l++) {
  57571. var points = lines[l];
  57572. for (var p = 0; p < points.length; p++) {
  57573. positions[i] = points[p].x;
  57574. positions[i + 1] = points[p].y;
  57575. positions[i + 2] = points[p].z;
  57576. if (colors && vertexColor) {
  57577. lineColors = colors[l];
  57578. vertexColor[c] = lineColors[p].r;
  57579. vertexColor[c + 1] = lineColors[p].g;
  57580. vertexColor[c + 2] = lineColors[p].b;
  57581. vertexColor[c + 3] = lineColors[p].a;
  57582. c += 4;
  57583. }
  57584. i += 3;
  57585. }
  57586. }
  57587. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  57588. if (colors && vertexColor) {
  57589. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  57590. }
  57591. return instance;
  57592. }
  57593. // line system creation
  57594. var useVertexColor = (colors) ? true : false;
  57595. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  57596. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  57597. vertexData.applyToMesh(lineSystem, options.updatable);
  57598. return lineSystem;
  57599. };
  57600. /**
  57601. * Creates a line mesh.
  57602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  57603. * 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.
  57604. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  57605. * The parameter `points` is an array successive Vector3.
  57606. * 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
  57607. * The optional parameter `colors` is an array of successive Color4, one per line point.
  57608. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  57609. * When updating an instance, remember that only point positions can change, not the number of points.
  57610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57611. */
  57612. MeshBuilder.CreateLines = function (name, options, scene) {
  57613. if (scene === void 0) { scene = null; }
  57614. var colors = (options.colors) ? [options.colors] : null;
  57615. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  57616. return lines;
  57617. };
  57618. /**
  57619. * Creates a dashed line mesh.
  57620. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  57621. * 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.
  57622. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  57623. * The parameter `points` is an array successive Vector3.
  57624. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  57625. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  57626. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  57627. * 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
  57628. * When updating an instance, remember that only point positions can change, not the number of points.
  57629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57630. */
  57631. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  57632. if (scene === void 0) { scene = null; }
  57633. var points = options.points;
  57634. var instance = options.instance;
  57635. var gapSize = options.gapSize || 1;
  57636. var dashSize = options.dashSize || 3;
  57637. if (instance) {
  57638. var positionFunction = function (positions) {
  57639. var curvect = BABYLON.Vector3.Zero();
  57640. var nbSeg = positions.length / 6;
  57641. var lg = 0;
  57642. var nb = 0;
  57643. var shft = 0;
  57644. var dashshft = 0;
  57645. var curshft = 0;
  57646. var p = 0;
  57647. var i = 0;
  57648. var j = 0;
  57649. for (i = 0; i < points.length - 1; i++) {
  57650. points[i + 1].subtractToRef(points[i], curvect);
  57651. lg += curvect.length();
  57652. }
  57653. shft = lg / nbSeg;
  57654. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  57655. for (i = 0; i < points.length - 1; i++) {
  57656. points[i + 1].subtractToRef(points[i], curvect);
  57657. nb = Math.floor(curvect.length() / shft);
  57658. curvect.normalize();
  57659. j = 0;
  57660. while (j < nb && p < positions.length) {
  57661. curshft = shft * j;
  57662. positions[p] = points[i].x + curshft * curvect.x;
  57663. positions[p + 1] = points[i].y + curshft * curvect.y;
  57664. positions[p + 2] = points[i].z + curshft * curvect.z;
  57665. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  57666. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  57667. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  57668. p += 6;
  57669. j++;
  57670. }
  57671. }
  57672. while (p < positions.length) {
  57673. positions[p] = points[i].x;
  57674. positions[p + 1] = points[i].y;
  57675. positions[p + 2] = points[i].z;
  57676. p += 3;
  57677. }
  57678. };
  57679. instance.updateMeshPositions(positionFunction, false);
  57680. return instance;
  57681. }
  57682. // dashed lines creation
  57683. var dashedLines = new BABYLON.LinesMesh(name, scene);
  57684. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  57685. vertexData.applyToMesh(dashedLines, options.updatable);
  57686. dashedLines.dashSize = dashSize;
  57687. dashedLines.gapSize = gapSize;
  57688. return dashedLines;
  57689. };
  57690. /**
  57691. * Creates an extruded shape mesh.
  57692. * 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.
  57693. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  57694. *
  57695. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57696. * 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
  57697. * extruded along the Z axis.
  57698. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57699. * 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.
  57700. * The parameter `scale` (float, default 1) is the value to scale the shape.
  57701. * 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
  57702. * 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
  57703. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57705. * 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).
  57706. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57707. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57709. */
  57710. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  57711. if (scene === void 0) { scene = null; }
  57712. var path = options.path;
  57713. var shape = options.shape;
  57714. var scale = options.scale || 1;
  57715. var rotation = options.rotation || 0;
  57716. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57717. var updatable = options.updatable;
  57718. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57719. var instance = options.instance || null;
  57720. var invertUV = options.invertUV || false;
  57721. 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);
  57722. };
  57723. /**
  57724. * Creates an custom extruded shape mesh.
  57725. * 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.
  57726. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  57727. *
  57728. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  57729. * 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
  57730. * extruded along the Z axis.
  57731. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  57732. * 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
  57733. * and the distance of this point from the begining of the path :
  57734. * ```javascript
  57735. * var rotationFunction = function(i, distance) {
  57736. * // do things
  57737. * return rotationValue; }
  57738. * ```
  57739. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  57740. * 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
  57741. * and the distance of this point from the begining of the path :
  57742. * ```javascript
  57743. * var scaleFunction = function(i, distance) {
  57744. * // do things
  57745. * return scaleValue;}
  57746. * ```
  57747. * It must returns a float value that will be the scale value applied to the shape on each path point.
  57748. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  57749. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  57750. * 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
  57751. * 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
  57752. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  57753. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57754. * 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).
  57755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57756. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57758. */
  57759. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  57760. var path = options.path;
  57761. var shape = options.shape;
  57762. var scaleFunction = options.scaleFunction || (function () { return 1; });
  57763. var rotationFunction = options.rotationFunction || (function () { return 0; });
  57764. var ribbonCloseArray = options.ribbonCloseArray || false;
  57765. var ribbonClosePath = options.ribbonClosePath || false;
  57766. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  57767. var updatable = options.updatable;
  57768. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57769. var instance = options.instance;
  57770. var invertUV = options.invertUV || false;
  57771. 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);
  57772. };
  57773. /**
  57774. * Creates lathe mesh.
  57775. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  57776. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  57777. *
  57778. * 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
  57779. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  57780. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  57781. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  57782. * 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.
  57783. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57784. * 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
  57785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57786. * 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).
  57787. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57788. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  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.CreateLathe = function (name, options, scene) {
  57792. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57793. var closed = (options.closed === undefined) ? true : options.closed;
  57794. var shape = options.shape;
  57795. var radius = options.radius || 1;
  57796. var tessellation = options.tessellation || 64;
  57797. var updatable = options.updatable;
  57798. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57799. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57800. var pi2 = Math.PI * 2;
  57801. var paths = new Array();
  57802. var invertUV = options.invertUV || false;
  57803. var i = 0;
  57804. var p = 0;
  57805. var step = pi2 / tessellation * arc;
  57806. var rotated;
  57807. var path = new Array();
  57808. ;
  57809. for (i = 0; i <= tessellation; i++) {
  57810. var path = [];
  57811. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57812. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57813. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57814. }
  57815. for (p = 0; p < shape.length; p++) {
  57816. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57817. path.push(rotated);
  57818. }
  57819. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57820. 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));
  57821. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57822. }
  57823. paths.push(path);
  57824. }
  57825. // lathe ribbon
  57826. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57827. return lathe;
  57828. };
  57829. /**
  57830. * Creates a plane mesh.
  57831. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57832. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57833. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57834. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57835. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57836. * 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).
  57837. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57838. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57839. */
  57840. MeshBuilder.CreatePlane = function (name, options, scene) {
  57841. var plane = new BABYLON.Mesh(name, scene);
  57842. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57843. plane._originalBuilderSideOrientation = options.sideOrientation;
  57844. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57845. vertexData.applyToMesh(plane, options.updatable);
  57846. if (options.sourcePlane) {
  57847. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57848. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57849. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57850. plane.rotate(vectorProduct, product);
  57851. }
  57852. return plane;
  57853. };
  57854. /**
  57855. * Creates a ground mesh.
  57856. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57857. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57858. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57859. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57860. */
  57861. MeshBuilder.CreateGround = function (name, options, scene) {
  57862. var ground = new BABYLON.GroundMesh(name, scene);
  57863. ground._setReady(false);
  57864. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57865. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57866. ground._width = options.width || 1;
  57867. ground._height = options.height || 1;
  57868. ground._maxX = ground._width / 2;
  57869. ground._maxZ = ground._height / 2;
  57870. ground._minX = -ground._maxX;
  57871. ground._minZ = -ground._maxZ;
  57872. var vertexData = BABYLON.VertexData.CreateGround(options);
  57873. vertexData.applyToMesh(ground, options.updatable);
  57874. ground._setReady(true);
  57875. return ground;
  57876. };
  57877. /**
  57878. * Creates a tiled ground mesh.
  57879. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57880. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57881. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57882. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57883. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57884. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57885. * numbers of subdivisions on the ground width and height of each tile.
  57886. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57887. */
  57888. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57889. var tiledGround = new BABYLON.Mesh(name, scene);
  57890. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57891. vertexData.applyToMesh(tiledGround, options.updatable);
  57892. return tiledGround;
  57893. };
  57894. /**
  57895. * Creates a ground mesh from a height map.
  57896. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57897. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57898. * The parameter `url` sets the URL of the height map image resource.
  57899. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57900. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57901. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57902. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57903. * 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.
  57904. * 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).
  57905. * This function is passed the newly built mesh :
  57906. * ```javascript
  57907. * function(mesh) { // do things
  57908. * return; }
  57909. * ```
  57910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57911. */
  57912. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57913. var width = options.width || 10.0;
  57914. var height = options.height || 10.0;
  57915. var subdivisions = options.subdivisions || 1 | 0;
  57916. var minHeight = options.minHeight || 0.0;
  57917. var maxHeight = options.maxHeight || 1.0;
  57918. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57919. var updatable = options.updatable;
  57920. var onReady = options.onReady;
  57921. var ground = new BABYLON.GroundMesh(name, scene);
  57922. ground._subdivisionsX = subdivisions;
  57923. ground._subdivisionsY = subdivisions;
  57924. ground._width = width;
  57925. ground._height = height;
  57926. ground._maxX = ground._width / 2.0;
  57927. ground._maxZ = ground._height / 2.0;
  57928. ground._minX = -ground._maxX;
  57929. ground._minZ = -ground._maxZ;
  57930. ground._setReady(false);
  57931. var onload = function (img) {
  57932. // Getting height map data
  57933. var canvas = document.createElement("canvas");
  57934. var context = canvas.getContext("2d");
  57935. if (!context) {
  57936. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57937. }
  57938. if (scene.isDisposed) {
  57939. return;
  57940. }
  57941. var bufferWidth = img.width;
  57942. var bufferHeight = img.height;
  57943. canvas.width = bufferWidth;
  57944. canvas.height = bufferHeight;
  57945. context.drawImage(img, 0, 0);
  57946. // Create VertexData from map data
  57947. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57948. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57949. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57950. width: width, height: height,
  57951. subdivisions: subdivisions,
  57952. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57953. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57954. });
  57955. vertexData.applyToMesh(ground, updatable);
  57956. //execute ready callback, if set
  57957. if (onReady) {
  57958. onReady(ground);
  57959. }
  57960. ground._setReady(true);
  57961. };
  57962. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57963. return ground;
  57964. };
  57965. /**
  57966. * Creates a polygon mesh.
  57967. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57968. * 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.
  57969. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57970. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57971. * 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).
  57972. * Remember you can only change the shape positions, not their number when updating a polygon.
  57973. */
  57974. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57975. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57976. var shape = options.shape;
  57977. var holes = options.holes || [];
  57978. var depth = options.depth || 0;
  57979. var contours = [];
  57980. var hole = [];
  57981. for (var i = 0; i < shape.length; i++) {
  57982. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57983. }
  57984. var epsilon = 0.00000001;
  57985. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57986. contours.pop();
  57987. }
  57988. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57989. for (var hNb = 0; hNb < holes.length; hNb++) {
  57990. hole = [];
  57991. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57992. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57993. }
  57994. polygonTriangulation.addHole(hole);
  57995. }
  57996. var polygon = polygonTriangulation.build(options.updatable, depth);
  57997. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57998. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57999. vertexData.applyToMesh(polygon, options.updatable);
  58000. return polygon;
  58001. };
  58002. ;
  58003. /**
  58004. * Creates an extruded polygon mesh, with depth in the Y direction.
  58005. * 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).
  58006. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  58007. */
  58008. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  58009. return MeshBuilder.CreatePolygon(name, options, scene);
  58010. };
  58011. ;
  58012. /**
  58013. * Creates a tube mesh.
  58014. * 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.
  58015. *
  58016. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  58017. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  58018. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  58019. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  58020. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  58021. * 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.
  58022. * It must return a radius value (positive float) :
  58023. * ```javascript
  58024. * var radiusFunction = function(i, distance) {
  58025. * // do things
  58026. * return radius; }
  58027. * ```
  58028. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  58029. * 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
  58030. * 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
  58031. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58032. * 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).
  58033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58034. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  58035. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58036. */
  58037. MeshBuilder.CreateTube = function (name, options, scene) {
  58038. var path = options.path;
  58039. var instance = options.instance;
  58040. var radius = 1.0;
  58041. if (instance) {
  58042. radius = instance.radius;
  58043. }
  58044. if (options.radius !== undefined) {
  58045. radius = options.radius;
  58046. }
  58047. ;
  58048. var tessellation = options.tessellation || 64 | 0;
  58049. var radiusFunction = options.radiusFunction || null;
  58050. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  58051. var invertUV = options.invertUV || false;
  58052. var updatable = options.updatable;
  58053. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58054. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  58055. // tube geometry
  58056. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  58057. var tangents = path3D.getTangents();
  58058. var normals = path3D.getNormals();
  58059. var distances = path3D.getDistances();
  58060. var pi2 = Math.PI * 2;
  58061. var step = pi2 / tessellation * arc;
  58062. var returnRadius = function () { return radius; };
  58063. var radiusFunctionFinal = radiusFunction || returnRadius;
  58064. var circlePath;
  58065. var rad;
  58066. var normal;
  58067. var rotated;
  58068. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  58069. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  58070. for (var i = 0; i < path.length; i++) {
  58071. rad = radiusFunctionFinal(i, distances[i]); // current radius
  58072. circlePath = Array(); // current circle array
  58073. normal = normals[i]; // current normal
  58074. for (var t = 0; t < tessellation; t++) {
  58075. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  58076. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  58077. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  58078. rotated.scaleInPlace(rad).addInPlace(path[i]);
  58079. circlePath[t] = rotated;
  58080. }
  58081. circlePaths[index] = circlePath;
  58082. index++;
  58083. }
  58084. // cap
  58085. var capPath = function (nbPoints, pathIndex) {
  58086. var pointCap = Array();
  58087. for (var i = 0; i < nbPoints; i++) {
  58088. pointCap.push(path[pathIndex]);
  58089. }
  58090. return pointCap;
  58091. };
  58092. switch (cap) {
  58093. case BABYLON.Mesh.NO_CAP:
  58094. break;
  58095. case BABYLON.Mesh.CAP_START:
  58096. circlePaths[0] = capPath(tessellation, 0);
  58097. circlePaths[1] = circlePaths[2].slice(0);
  58098. break;
  58099. case BABYLON.Mesh.CAP_END:
  58100. circlePaths[index] = circlePaths[index - 1].slice(0);
  58101. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  58102. break;
  58103. case BABYLON.Mesh.CAP_ALL:
  58104. circlePaths[0] = capPath(tessellation, 0);
  58105. circlePaths[1] = circlePaths[2].slice(0);
  58106. circlePaths[index] = circlePaths[index - 1].slice(0);
  58107. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  58108. break;
  58109. default:
  58110. break;
  58111. }
  58112. return circlePaths;
  58113. };
  58114. var path3D;
  58115. var pathArray;
  58116. if (instance) {
  58117. var arc = options.arc || instance.arc;
  58118. path3D = (instance.path3D).update(path);
  58119. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  58120. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  58121. instance.path3D = path3D;
  58122. instance.pathArray = pathArray;
  58123. instance.arc = arc;
  58124. instance.radius = radius;
  58125. return instance;
  58126. }
  58127. // tube creation
  58128. path3D = new BABYLON.Path3D(path);
  58129. var newPathArray = new Array();
  58130. cap = (cap < 0 || cap > 3) ? 0 : cap;
  58131. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  58132. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  58133. tube.pathArray = pathArray;
  58134. tube.path3D = path3D;
  58135. tube.tessellation = tessellation;
  58136. tube.cap = cap;
  58137. tube.arc = options.arc;
  58138. tube.radius = radius;
  58139. return tube;
  58140. };
  58141. /**
  58142. * Creates a polyhedron mesh.
  58143. *
  58144. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  58145. * 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
  58146. * to choose the wanted type.
  58147. * The parameter `size` (positive float, default 1) sets the polygon size.
  58148. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  58149. * 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`.
  58150. * 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
  58151. * 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)`).
  58152. * 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
  58153. * 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.
  58154. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  58155. * 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).
  58156. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  58157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  58158. */
  58159. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  58160. var polyhedron = new BABYLON.Mesh(name, scene);
  58161. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  58162. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  58163. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  58164. vertexData.applyToMesh(polyhedron, options.updatable);
  58165. return polyhedron;
  58166. };
  58167. /**
  58168. * Creates a decal mesh.
  58169. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  58170. * 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.
  58171. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  58172. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  58173. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  58174. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  58175. */
  58176. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  58177. var indices = sourceMesh.getIndices();
  58178. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58179. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58180. var position = options.position || BABYLON.Vector3.Zero();
  58181. var normal = options.normal || BABYLON.Vector3.Up();
  58182. var size = options.size || BABYLON.Vector3.One();
  58183. var angle = options.angle || 0;
  58184. // Getting correct rotation
  58185. if (!normal) {
  58186. var target = new BABYLON.Vector3(0, 0, 1);
  58187. var camera = sourceMesh.getScene().activeCamera;
  58188. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  58189. normal = camera.globalPosition.subtract(cameraWorldTarget);
  58190. }
  58191. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  58192. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  58193. var pitch = Math.atan2(normal.y, len);
  58194. // Matrix
  58195. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  58196. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  58197. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  58198. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  58199. var vertexData = new BABYLON.VertexData();
  58200. vertexData.indices = [];
  58201. vertexData.positions = [];
  58202. vertexData.normals = [];
  58203. vertexData.uvs = [];
  58204. var currentVertexDataIndex = 0;
  58205. var extractDecalVector3 = function (indexId) {
  58206. var result = new BABYLON.PositionNormalVertex();
  58207. if (!indices || !positions || !normals) {
  58208. return result;
  58209. }
  58210. var vertexId = indices[indexId];
  58211. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  58212. // Send vector to decal local world
  58213. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  58214. // Get normal
  58215. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  58216. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  58217. return result;
  58218. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  58219. var clip = function (vertices, axis) {
  58220. if (vertices.length === 0) {
  58221. return vertices;
  58222. }
  58223. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  58224. var clipVertices = function (v0, v1) {
  58225. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  58226. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  58227. };
  58228. var result = new Array();
  58229. for (var index = 0; index < vertices.length; index += 3) {
  58230. var v1Out;
  58231. var v2Out;
  58232. var v3Out;
  58233. var total = 0;
  58234. var nV1 = null;
  58235. var nV2 = null;
  58236. var nV3 = null;
  58237. var nV4 = null;
  58238. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  58239. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  58240. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  58241. v1Out = d1 > 0;
  58242. v2Out = d2 > 0;
  58243. v3Out = d3 > 0;
  58244. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  58245. switch (total) {
  58246. case 0:
  58247. result.push(vertices[index]);
  58248. result.push(vertices[index + 1]);
  58249. result.push(vertices[index + 2]);
  58250. break;
  58251. case 1:
  58252. if (v1Out) {
  58253. nV1 = vertices[index + 1];
  58254. nV2 = vertices[index + 2];
  58255. nV3 = clipVertices(vertices[index], nV1);
  58256. nV4 = clipVertices(vertices[index], nV2);
  58257. }
  58258. if (v2Out) {
  58259. nV1 = vertices[index];
  58260. nV2 = vertices[index + 2];
  58261. nV3 = clipVertices(vertices[index + 1], nV1);
  58262. nV4 = clipVertices(vertices[index + 1], nV2);
  58263. result.push(nV3);
  58264. result.push(nV2.clone());
  58265. result.push(nV1.clone());
  58266. result.push(nV2.clone());
  58267. result.push(nV3.clone());
  58268. result.push(nV4);
  58269. break;
  58270. }
  58271. if (v3Out) {
  58272. nV1 = vertices[index];
  58273. nV2 = vertices[index + 1];
  58274. nV3 = clipVertices(vertices[index + 2], nV1);
  58275. nV4 = clipVertices(vertices[index + 2], nV2);
  58276. }
  58277. if (nV1 && nV2 && nV3 && nV4) {
  58278. result.push(nV1.clone());
  58279. result.push(nV2.clone());
  58280. result.push(nV3);
  58281. result.push(nV4);
  58282. result.push(nV3.clone());
  58283. result.push(nV2.clone());
  58284. }
  58285. break;
  58286. case 2:
  58287. if (!v1Out) {
  58288. nV1 = vertices[index].clone();
  58289. nV2 = clipVertices(nV1, vertices[index + 1]);
  58290. nV3 = clipVertices(nV1, vertices[index + 2]);
  58291. result.push(nV1);
  58292. result.push(nV2);
  58293. result.push(nV3);
  58294. }
  58295. if (!v2Out) {
  58296. nV1 = vertices[index + 1].clone();
  58297. nV2 = clipVertices(nV1, vertices[index + 2]);
  58298. nV3 = clipVertices(nV1, vertices[index]);
  58299. result.push(nV1);
  58300. result.push(nV2);
  58301. result.push(nV3);
  58302. }
  58303. if (!v3Out) {
  58304. nV1 = vertices[index + 2].clone();
  58305. nV2 = clipVertices(nV1, vertices[index]);
  58306. nV3 = clipVertices(nV1, vertices[index + 1]);
  58307. result.push(nV1);
  58308. result.push(nV2);
  58309. result.push(nV3);
  58310. }
  58311. break;
  58312. case 3:
  58313. break;
  58314. }
  58315. }
  58316. return result;
  58317. };
  58318. for (var index = 0; index < indices.length; index += 3) {
  58319. var faceVertices = new Array();
  58320. faceVertices.push(extractDecalVector3(index));
  58321. faceVertices.push(extractDecalVector3(index + 1));
  58322. faceVertices.push(extractDecalVector3(index + 2));
  58323. // Clip
  58324. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  58325. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  58326. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  58327. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  58328. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  58329. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  58330. if (faceVertices.length === 0) {
  58331. continue;
  58332. }
  58333. // Add UVs and get back to world
  58334. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  58335. var vertex = faceVertices[vIndex];
  58336. //TODO check for Int32Array | Uint32Array | Uint16Array
  58337. vertexData.indices.push(currentVertexDataIndex);
  58338. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  58339. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  58340. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  58341. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  58342. currentVertexDataIndex++;
  58343. }
  58344. }
  58345. // Return mesh
  58346. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  58347. vertexData.applyToMesh(decal);
  58348. decal.position = position.clone();
  58349. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  58350. return decal;
  58351. };
  58352. // Privates
  58353. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  58354. // extrusion geometry
  58355. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  58356. var tangents = path3D.getTangents();
  58357. var normals = path3D.getNormals();
  58358. var binormals = path3D.getBinormals();
  58359. var distances = path3D.getDistances();
  58360. var angle = 0;
  58361. var returnScale = function () { return scale !== null ? scale : 1; };
  58362. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  58363. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  58364. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  58365. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  58366. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  58367. for (var i = 0; i < curve.length; i++) {
  58368. var shapePath = new Array();
  58369. var angleStep = rotate(i, distances[i]);
  58370. var scaleRatio = scl(i, distances[i]);
  58371. for (var p = 0; p < shape.length; p++) {
  58372. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  58373. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  58374. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  58375. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  58376. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  58377. shapePath[p] = rotated;
  58378. }
  58379. shapePaths[index] = shapePath;
  58380. angle += angleStep;
  58381. index++;
  58382. }
  58383. // cap
  58384. var capPath = function (shapePath) {
  58385. var pointCap = Array();
  58386. var barycenter = BABYLON.Vector3.Zero();
  58387. var i;
  58388. for (i = 0; i < shapePath.length; i++) {
  58389. barycenter.addInPlace(shapePath[i]);
  58390. }
  58391. barycenter.scaleInPlace(1.0 / shapePath.length);
  58392. for (i = 0; i < shapePath.length; i++) {
  58393. pointCap.push(barycenter);
  58394. }
  58395. return pointCap;
  58396. };
  58397. switch (cap) {
  58398. case BABYLON.Mesh.NO_CAP:
  58399. break;
  58400. case BABYLON.Mesh.CAP_START:
  58401. shapePaths[0] = capPath(shapePaths[2]);
  58402. shapePaths[1] = shapePaths[2];
  58403. break;
  58404. case BABYLON.Mesh.CAP_END:
  58405. shapePaths[index] = shapePaths[index - 1];
  58406. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  58407. break;
  58408. case BABYLON.Mesh.CAP_ALL:
  58409. shapePaths[0] = capPath(shapePaths[2]);
  58410. shapePaths[1] = shapePaths[2];
  58411. shapePaths[index] = shapePaths[index - 1];
  58412. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  58413. break;
  58414. default:
  58415. break;
  58416. }
  58417. return shapePaths;
  58418. };
  58419. var path3D;
  58420. var pathArray;
  58421. if (instance) {
  58422. path3D = (instance.path3D).update(curve);
  58423. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  58424. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  58425. return instance;
  58426. }
  58427. // extruded shape creation
  58428. path3D = new BABYLON.Path3D(curve);
  58429. var newShapePaths = new Array();
  58430. cap = (cap < 0 || cap > 3) ? 0 : cap;
  58431. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  58432. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  58433. extrudedGeneric.pathArray = pathArray;
  58434. extrudedGeneric.path3D = path3D;
  58435. extrudedGeneric.cap = cap;
  58436. return extrudedGeneric;
  58437. };
  58438. return MeshBuilder;
  58439. }());
  58440. BABYLON.MeshBuilder = MeshBuilder;
  58441. })(BABYLON || (BABYLON = {}));
  58442. //# sourceMappingURL=babylon.meshBuilder.js.map
  58443. "use strict";
  58444. var BABYLON;
  58445. (function (BABYLON) {
  58446. /**
  58447. * Draco compression (https://google.github.io/draco/)
  58448. */
  58449. var DracoCompression = /** @class */ (function () {
  58450. /**
  58451. * Constructor
  58452. * @param numWorkers The number of workers for async operations
  58453. */
  58454. function DracoCompression(numWorkers) {
  58455. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  58456. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  58457. if (!workerBlobUrl || !Worker) {
  58458. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  58459. return;
  58460. }
  58461. var workers = new Array(numWorkers);
  58462. for (var i = 0; i < workers.length; i++) {
  58463. var worker = new Worker(workerBlobUrl);
  58464. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  58465. workers[i] = worker;
  58466. }
  58467. this._workerPool = new BABYLON.WorkerPool(workers);
  58468. }
  58469. /**
  58470. * Stop all async operations and release resources.
  58471. */
  58472. DracoCompression.prototype.dispose = function () {
  58473. this._workerPool.dispose();
  58474. delete this._workerPool;
  58475. };
  58476. /**
  58477. * Decode Draco compressed mesh data to vertex data.
  58478. * @param data The array buffer view for the Draco compression data
  58479. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  58480. * @returns A promise that resolves with the decoded vertex data
  58481. */
  58482. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  58483. var _this = this;
  58484. return new Promise(function (resolve, reject) {
  58485. _this._workerPool.push(function (worker, onComplete) {
  58486. var vertexData = new BABYLON.VertexData();
  58487. var onError = function (error) {
  58488. worker.removeEventListener("error", onError);
  58489. worker.removeEventListener("message", onMessage);
  58490. reject(error);
  58491. onComplete();
  58492. };
  58493. var onMessage = function (message) {
  58494. if (message.data === "done") {
  58495. worker.removeEventListener("error", onError);
  58496. worker.removeEventListener("message", onMessage);
  58497. resolve(vertexData);
  58498. onComplete();
  58499. }
  58500. else if (message.data.id === "indices") {
  58501. vertexData.indices = message.data.value;
  58502. }
  58503. else {
  58504. vertexData.set(message.data.value, message.data.id);
  58505. }
  58506. };
  58507. worker.addEventListener("error", onError);
  58508. worker.addEventListener("message", onMessage);
  58509. var dataCopy = new Uint8Array(data.byteLength);
  58510. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  58511. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  58512. });
  58513. });
  58514. };
  58515. /**
  58516. * The worker function that gets converted to a blob url to pass into a worker.
  58517. */
  58518. DracoCompression._Worker = function () {
  58519. // self is actually a DedicatedWorkerGlobalScope
  58520. var _self = self;
  58521. var decodeMesh = function (data, attributes) {
  58522. var dracoModule = new DracoDecoderModule();
  58523. var buffer = new dracoModule.DecoderBuffer();
  58524. buffer.Init(data, data.byteLength);
  58525. var decoder = new dracoModule.Decoder();
  58526. var geometry;
  58527. var status;
  58528. try {
  58529. var type = decoder.GetEncodedGeometryType(buffer);
  58530. switch (type) {
  58531. case dracoModule.TRIANGULAR_MESH:
  58532. geometry = new dracoModule.Mesh();
  58533. status = decoder.DecodeBufferToMesh(buffer, geometry);
  58534. break;
  58535. case dracoModule.POINT_CLOUD:
  58536. geometry = new dracoModule.PointCloud();
  58537. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  58538. break;
  58539. default:
  58540. throw new Error("Invalid geometry type " + type);
  58541. }
  58542. if (!status.ok() || !geometry.ptr) {
  58543. throw new Error(status.error_msg());
  58544. }
  58545. var numPoints = geometry.num_points();
  58546. if (type === dracoModule.TRIANGULAR_MESH) {
  58547. var numFaces = geometry.num_faces();
  58548. var faceIndices = new dracoModule.DracoInt32Array();
  58549. try {
  58550. var indices = new Uint32Array(numFaces * 3);
  58551. for (var i = 0; i < numFaces; i++) {
  58552. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  58553. var offset = i * 3;
  58554. indices[offset + 0] = faceIndices.GetValue(0);
  58555. indices[offset + 1] = faceIndices.GetValue(1);
  58556. indices[offset + 2] = faceIndices.GetValue(2);
  58557. }
  58558. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  58559. }
  58560. finally {
  58561. dracoModule.destroy(faceIndices);
  58562. }
  58563. }
  58564. for (var kind in attributes) {
  58565. var uniqueId = attributes[kind];
  58566. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  58567. var dracoData = new dracoModule.DracoFloat32Array();
  58568. try {
  58569. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  58570. var babylonData = new Float32Array(numPoints * attribute.num_components());
  58571. for (var i = 0; i < babylonData.length; i++) {
  58572. babylonData[i] = dracoData.GetValue(i);
  58573. }
  58574. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  58575. }
  58576. finally {
  58577. dracoModule.destroy(dracoData);
  58578. }
  58579. }
  58580. }
  58581. finally {
  58582. if (geometry) {
  58583. dracoModule.destroy(geometry);
  58584. }
  58585. dracoModule.destroy(decoder);
  58586. dracoModule.destroy(buffer);
  58587. }
  58588. _self.postMessage("done");
  58589. };
  58590. _self.onmessage = function (event) {
  58591. switch (event.data.id) {
  58592. case "initDecoder": {
  58593. importScripts(event.data.url);
  58594. break;
  58595. }
  58596. case "decodeMesh": {
  58597. decodeMesh(event.data.data, event.data.attributes);
  58598. break;
  58599. }
  58600. }
  58601. };
  58602. };
  58603. DracoCompression._GetDefaultDecoderUrl = function () {
  58604. if (!BABYLON.Tools.IsWindowObjectExist()) {
  58605. return null;
  58606. }
  58607. for (var i = 0; i < document.scripts.length; i++) {
  58608. if (document.scripts[i].type === "text/x-draco-decoder") {
  58609. return document.scripts[i].src;
  58610. }
  58611. }
  58612. return null;
  58613. };
  58614. /**
  58615. * Gets the url to the draco decoder if available.
  58616. */
  58617. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  58618. return DracoCompression;
  58619. }());
  58620. BABYLON.DracoCompression = DracoCompression;
  58621. })(BABYLON || (BABYLON = {}));
  58622. //# sourceMappingURL=babylon.dracoCompression.js.map
  58623. "use strict";
  58624. var BABYLON;
  58625. (function (BABYLON) {
  58626. var AudioEngine = /** @class */ (function () {
  58627. function AudioEngine() {
  58628. this._audioContext = null;
  58629. this._audioContextInitialized = false;
  58630. this.canUseWebAudio = false;
  58631. this.WarnedWebAudioUnsupported = false;
  58632. this.unlocked = false;
  58633. this.isMP3supported = false;
  58634. this.isOGGsupported = false;
  58635. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  58636. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  58637. this.canUseWebAudio = true;
  58638. }
  58639. var audioElem = document.createElement('audio');
  58640. try {
  58641. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  58642. this.isMP3supported = true;
  58643. }
  58644. }
  58645. catch (e) {
  58646. // protect error during capability check.
  58647. }
  58648. try {
  58649. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  58650. this.isOGGsupported = true;
  58651. }
  58652. }
  58653. catch (e) {
  58654. // protect error during capability check.
  58655. }
  58656. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  58657. this._unlockiOSaudio();
  58658. }
  58659. else {
  58660. this.unlocked = true;
  58661. }
  58662. }
  58663. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  58664. get: function () {
  58665. if (!this._audioContextInitialized) {
  58666. this._initializeAudioContext();
  58667. }
  58668. return this._audioContext;
  58669. },
  58670. enumerable: true,
  58671. configurable: true
  58672. });
  58673. AudioEngine.prototype._unlockiOSaudio = function () {
  58674. var _this = this;
  58675. var unlockaudio = function () {
  58676. if (!_this.audioContext) {
  58677. return;
  58678. }
  58679. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  58680. var source = _this.audioContext.createBufferSource();
  58681. source.buffer = buffer;
  58682. source.connect(_this.audioContext.destination);
  58683. source.start(0);
  58684. setTimeout(function () {
  58685. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  58686. _this.unlocked = true;
  58687. window.removeEventListener('touchend', unlockaudio, false);
  58688. if (_this.onAudioUnlocked) {
  58689. _this.onAudioUnlocked();
  58690. }
  58691. }
  58692. }, 0);
  58693. };
  58694. window.addEventListener('touchend', unlockaudio, false);
  58695. };
  58696. AudioEngine.prototype._initializeAudioContext = function () {
  58697. try {
  58698. if (this.canUseWebAudio) {
  58699. this._audioContext = new AudioContext();
  58700. // create a global volume gain node
  58701. this.masterGain = this._audioContext.createGain();
  58702. this.masterGain.gain.value = 1;
  58703. this.masterGain.connect(this._audioContext.destination);
  58704. this._audioContextInitialized = true;
  58705. }
  58706. }
  58707. catch (e) {
  58708. this.canUseWebAudio = false;
  58709. BABYLON.Tools.Error("Web Audio: " + e.message);
  58710. }
  58711. };
  58712. AudioEngine.prototype.dispose = function () {
  58713. if (this.canUseWebAudio && this._audioContextInitialized) {
  58714. if (this._connectedAnalyser && this._audioContext) {
  58715. this._connectedAnalyser.stopDebugCanvas();
  58716. this._connectedAnalyser.dispose();
  58717. this.masterGain.disconnect();
  58718. this.masterGain.connect(this._audioContext.destination);
  58719. this._connectedAnalyser = null;
  58720. }
  58721. this.masterGain.gain.value = 1;
  58722. }
  58723. this.WarnedWebAudioUnsupported = false;
  58724. };
  58725. AudioEngine.prototype.getGlobalVolume = function () {
  58726. if (this.canUseWebAudio && this._audioContextInitialized) {
  58727. return this.masterGain.gain.value;
  58728. }
  58729. else {
  58730. return -1;
  58731. }
  58732. };
  58733. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  58734. if (this.canUseWebAudio && this._audioContextInitialized) {
  58735. this.masterGain.gain.value = newVolume;
  58736. }
  58737. };
  58738. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  58739. if (this._connectedAnalyser) {
  58740. this._connectedAnalyser.stopDebugCanvas();
  58741. }
  58742. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  58743. this._connectedAnalyser = analyser;
  58744. this.masterGain.disconnect();
  58745. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  58746. }
  58747. };
  58748. return AudioEngine;
  58749. }());
  58750. BABYLON.AudioEngine = AudioEngine;
  58751. })(BABYLON || (BABYLON = {}));
  58752. //# sourceMappingURL=babylon.audioEngine.js.map
  58753. "use strict";
  58754. var BABYLON;
  58755. (function (BABYLON) {
  58756. var Sound = /** @class */ (function () {
  58757. /**
  58758. * Create a sound and attach it to a scene
  58759. * @param name Name of your sound
  58760. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  58761. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  58762. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  58763. */
  58764. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  58765. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  58766. var _this = this;
  58767. this.autoplay = false;
  58768. this.loop = false;
  58769. this.useCustomAttenuation = false;
  58770. this.spatialSound = false;
  58771. this.refDistance = 1;
  58772. this.rolloffFactor = 1;
  58773. this.maxDistance = 100;
  58774. this.distanceModel = "linear";
  58775. this._panningModel = "equalpower";
  58776. this._playbackRate = 1;
  58777. this._streaming = false;
  58778. this._startTime = 0;
  58779. this._startOffset = 0;
  58780. this._position = BABYLON.Vector3.Zero();
  58781. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  58782. this._volume = 1;
  58783. this._isReadyToPlay = false;
  58784. this.isPlaying = false;
  58785. this.isPaused = false;
  58786. this._isDirectional = false;
  58787. // Used if you'd like to create a directional sound.
  58788. // If not set, the sound will be omnidirectional
  58789. this._coneInnerAngle = 360;
  58790. this._coneOuterAngle = 360;
  58791. this._coneOuterGain = 0;
  58792. this._isOutputConnected = false;
  58793. this._urlType = "Unknown";
  58794. this.name = name;
  58795. this._scene = scene;
  58796. this._readyToPlayCallback = readyToPlayCallback;
  58797. // Default custom attenuation function is a linear attenuation
  58798. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58799. if (currentDistance < maxDistance) {
  58800. return currentVolume * (1 - currentDistance / maxDistance);
  58801. }
  58802. else {
  58803. return 0;
  58804. }
  58805. };
  58806. if (options) {
  58807. this.autoplay = options.autoplay || false;
  58808. this.loop = options.loop || false;
  58809. // if volume === 0, we need another way to check this option
  58810. if (options.volume !== undefined) {
  58811. this._volume = options.volume;
  58812. }
  58813. this.spatialSound = options.spatialSound || false;
  58814. this.maxDistance = options.maxDistance || 100;
  58815. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58816. this.rolloffFactor = options.rolloffFactor || 1;
  58817. this.refDistance = options.refDistance || 1;
  58818. this.distanceModel = options.distanceModel || "linear";
  58819. this._playbackRate = options.playbackRate || 1;
  58820. this._streaming = options.streaming || false;
  58821. }
  58822. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58823. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58824. this._soundGain.gain.value = this._volume;
  58825. this._inputAudioNode = this._soundGain;
  58826. this._ouputAudioNode = this._soundGain;
  58827. if (this.spatialSound) {
  58828. this._createSpatialParameters();
  58829. }
  58830. this._scene.mainSoundTrack.AddSound(this);
  58831. var validParameter = true;
  58832. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58833. if (urlOrArrayBuffer) {
  58834. try {
  58835. if (typeof (urlOrArrayBuffer) === "string")
  58836. this._urlType = "String";
  58837. if (Array.isArray(urlOrArrayBuffer))
  58838. this._urlType = "Array";
  58839. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58840. this._urlType = "ArrayBuffer";
  58841. var urls = [];
  58842. var codecSupportedFound = false;
  58843. switch (this._urlType) {
  58844. case "ArrayBuffer":
  58845. if (urlOrArrayBuffer.byteLength > 0) {
  58846. codecSupportedFound = true;
  58847. this._soundLoaded(urlOrArrayBuffer);
  58848. }
  58849. break;
  58850. case "String":
  58851. urls.push(urlOrArrayBuffer);
  58852. case "Array":
  58853. if (urls.length === 0)
  58854. urls = urlOrArrayBuffer;
  58855. // If we found a supported format, we load it immediately and stop the loop
  58856. for (var i = 0; i < urls.length; i++) {
  58857. var url = urls[i];
  58858. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58859. codecSupportedFound = true;
  58860. }
  58861. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58862. codecSupportedFound = true;
  58863. }
  58864. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58865. codecSupportedFound = true;
  58866. }
  58867. if (url.indexOf("blob:") !== -1) {
  58868. codecSupportedFound = true;
  58869. }
  58870. if (codecSupportedFound) {
  58871. // Loading sound using XHR2
  58872. if (!this._streaming) {
  58873. this._scene._loadFile(url, function (data) {
  58874. _this._soundLoaded(data);
  58875. }, undefined, true, true, function (exception) {
  58876. if (exception) {
  58877. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58878. }
  58879. BABYLON.Tools.Error("Sound creation aborted.");
  58880. _this._scene.mainSoundTrack.RemoveSound(_this);
  58881. });
  58882. }
  58883. else {
  58884. this._htmlAudioElement = new Audio(url);
  58885. this._htmlAudioElement.controls = false;
  58886. this._htmlAudioElement.loop = this.loop;
  58887. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58888. this._htmlAudioElement.preload = "auto";
  58889. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58890. _this._isReadyToPlay = true;
  58891. if (_this.autoplay) {
  58892. _this.play();
  58893. }
  58894. if (_this._readyToPlayCallback) {
  58895. _this._readyToPlayCallback();
  58896. }
  58897. });
  58898. document.body.appendChild(this._htmlAudioElement);
  58899. }
  58900. break;
  58901. }
  58902. }
  58903. break;
  58904. default:
  58905. validParameter = false;
  58906. break;
  58907. }
  58908. if (!validParameter) {
  58909. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58910. }
  58911. else {
  58912. if (!codecSupportedFound) {
  58913. this._isReadyToPlay = true;
  58914. // Simulating a ready to play event to avoid breaking code path
  58915. if (this._readyToPlayCallback) {
  58916. window.setTimeout(function () {
  58917. if (_this._readyToPlayCallback) {
  58918. _this._readyToPlayCallback();
  58919. }
  58920. }, 1000);
  58921. }
  58922. }
  58923. }
  58924. }
  58925. catch (ex) {
  58926. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58927. this._scene.mainSoundTrack.RemoveSound(this);
  58928. }
  58929. }
  58930. }
  58931. else {
  58932. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58933. this._scene.mainSoundTrack.AddSound(this);
  58934. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58935. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58936. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58937. }
  58938. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58939. if (this._readyToPlayCallback) {
  58940. window.setTimeout(function () {
  58941. if (_this._readyToPlayCallback) {
  58942. _this._readyToPlayCallback();
  58943. }
  58944. }, 1000);
  58945. }
  58946. }
  58947. }
  58948. Sound.prototype.dispose = function () {
  58949. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58950. if (this.isPlaying) {
  58951. this.stop();
  58952. }
  58953. this._isReadyToPlay = false;
  58954. if (this.soundTrackId === -1) {
  58955. this._scene.mainSoundTrack.RemoveSound(this);
  58956. }
  58957. else {
  58958. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58959. }
  58960. if (this._soundGain) {
  58961. this._soundGain.disconnect();
  58962. this._soundGain = null;
  58963. }
  58964. if (this._soundPanner) {
  58965. this._soundPanner.disconnect();
  58966. this._soundPanner = null;
  58967. }
  58968. if (this._soundSource) {
  58969. this._soundSource.disconnect();
  58970. this._soundSource = null;
  58971. }
  58972. this._audioBuffer = null;
  58973. if (this._htmlAudioElement) {
  58974. this._htmlAudioElement.pause();
  58975. this._htmlAudioElement.src = "";
  58976. document.body.removeChild(this._htmlAudioElement);
  58977. }
  58978. if (this._connectedMesh && this._registerFunc) {
  58979. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58980. this._connectedMesh = null;
  58981. }
  58982. }
  58983. };
  58984. Sound.prototype.isReady = function () {
  58985. return this._isReadyToPlay;
  58986. };
  58987. Sound.prototype._soundLoaded = function (audioData) {
  58988. var _this = this;
  58989. if (!BABYLON.Engine.audioEngine.audioContext) {
  58990. return;
  58991. }
  58992. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58993. _this._audioBuffer = buffer;
  58994. _this._isReadyToPlay = true;
  58995. if (_this.autoplay) {
  58996. _this.play();
  58997. }
  58998. if (_this._readyToPlayCallback) {
  58999. _this._readyToPlayCallback();
  59000. }
  59001. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  59002. };
  59003. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  59004. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59005. this._audioBuffer = audioBuffer;
  59006. this._isReadyToPlay = true;
  59007. }
  59008. };
  59009. Sound.prototype.updateOptions = function (options) {
  59010. if (options) {
  59011. this.loop = options.loop || this.loop;
  59012. this.maxDistance = options.maxDistance || this.maxDistance;
  59013. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  59014. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  59015. this.refDistance = options.refDistance || this.refDistance;
  59016. this.distanceModel = options.distanceModel || this.distanceModel;
  59017. this._playbackRate = options.playbackRate || this._playbackRate;
  59018. this._updateSpatialParameters();
  59019. if (this.isPlaying) {
  59020. if (this._streaming) {
  59021. this._htmlAudioElement.playbackRate = this._playbackRate;
  59022. }
  59023. else {
  59024. if (this._soundSource) {
  59025. this._soundSource.playbackRate.value = this._playbackRate;
  59026. }
  59027. }
  59028. }
  59029. }
  59030. };
  59031. Sound.prototype._createSpatialParameters = function () {
  59032. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  59033. if (this._scene.headphone) {
  59034. this._panningModel = "HRTF";
  59035. }
  59036. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  59037. this._updateSpatialParameters();
  59038. this._soundPanner.connect(this._ouputAudioNode);
  59039. this._inputAudioNode = this._soundPanner;
  59040. }
  59041. };
  59042. Sound.prototype._updateSpatialParameters = function () {
  59043. if (this.spatialSound && this._soundPanner) {
  59044. if (this.useCustomAttenuation) {
  59045. // Tricks to disable in a way embedded Web Audio attenuation
  59046. this._soundPanner.distanceModel = "linear";
  59047. this._soundPanner.maxDistance = Number.MAX_VALUE;
  59048. this._soundPanner.refDistance = 1;
  59049. this._soundPanner.rolloffFactor = 1;
  59050. this._soundPanner.panningModel = this._panningModel;
  59051. }
  59052. else {
  59053. this._soundPanner.distanceModel = this.distanceModel;
  59054. this._soundPanner.maxDistance = this.maxDistance;
  59055. this._soundPanner.refDistance = this.refDistance;
  59056. this._soundPanner.rolloffFactor = this.rolloffFactor;
  59057. this._soundPanner.panningModel = this._panningModel;
  59058. }
  59059. }
  59060. };
  59061. Sound.prototype.switchPanningModelToHRTF = function () {
  59062. this._panningModel = "HRTF";
  59063. this._switchPanningModel();
  59064. };
  59065. Sound.prototype.switchPanningModelToEqualPower = function () {
  59066. this._panningModel = "equalpower";
  59067. this._switchPanningModel();
  59068. };
  59069. Sound.prototype._switchPanningModel = function () {
  59070. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  59071. this._soundPanner.panningModel = this._panningModel;
  59072. }
  59073. };
  59074. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  59075. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59076. if (this._isOutputConnected) {
  59077. this._ouputAudioNode.disconnect();
  59078. }
  59079. this._ouputAudioNode.connect(soundTrackAudioNode);
  59080. this._isOutputConnected = true;
  59081. }
  59082. };
  59083. /**
  59084. * Transform this sound into a directional source
  59085. * @param coneInnerAngle Size of the inner cone in degree
  59086. * @param coneOuterAngle Size of the outer cone in degree
  59087. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  59088. */
  59089. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  59090. if (coneOuterAngle < coneInnerAngle) {
  59091. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  59092. return;
  59093. }
  59094. this._coneInnerAngle = coneInnerAngle;
  59095. this._coneOuterAngle = coneOuterAngle;
  59096. this._coneOuterGain = coneOuterGain;
  59097. this._isDirectional = true;
  59098. if (this.isPlaying && this.loop) {
  59099. this.stop();
  59100. this.play();
  59101. }
  59102. };
  59103. Sound.prototype.setPosition = function (newPosition) {
  59104. this._position = newPosition;
  59105. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  59106. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  59107. }
  59108. };
  59109. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  59110. this._localDirection = newLocalDirection;
  59111. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  59112. this._updateDirection();
  59113. }
  59114. };
  59115. Sound.prototype._updateDirection = function () {
  59116. if (!this._connectedMesh || !this._soundPanner) {
  59117. return;
  59118. }
  59119. var mat = this._connectedMesh.getWorldMatrix();
  59120. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  59121. direction.normalize();
  59122. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  59123. };
  59124. Sound.prototype.updateDistanceFromListener = function () {
  59125. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  59126. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  59127. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  59128. }
  59129. };
  59130. Sound.prototype.setAttenuationFunction = function (callback) {
  59131. this._customAttenuationFunction = callback;
  59132. };
  59133. /**
  59134. * Play the sound
  59135. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  59136. * @param offset (optional) Start the sound setting it at a specific time
  59137. */
  59138. Sound.prototype.play = function (time, offset) {
  59139. var _this = this;
  59140. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  59141. try {
  59142. if (this._startOffset < 0) {
  59143. time = -this._startOffset;
  59144. this._startOffset = 0;
  59145. }
  59146. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  59147. if (!this._soundSource || !this._streamingSource) {
  59148. if (this.spatialSound && this._soundPanner) {
  59149. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  59150. if (this._isDirectional) {
  59151. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  59152. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  59153. this._soundPanner.coneOuterGain = this._coneOuterGain;
  59154. if (this._connectedMesh) {
  59155. this._updateDirection();
  59156. }
  59157. else {
  59158. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  59159. }
  59160. }
  59161. }
  59162. }
  59163. if (this._streaming) {
  59164. if (!this._streamingSource) {
  59165. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  59166. this._htmlAudioElement.onended = function () { _this._onended(); };
  59167. this._htmlAudioElement.playbackRate = this._playbackRate;
  59168. }
  59169. this._streamingSource.disconnect();
  59170. this._streamingSource.connect(this._inputAudioNode);
  59171. this._htmlAudioElement.play();
  59172. }
  59173. else {
  59174. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  59175. this._soundSource.buffer = this._audioBuffer;
  59176. this._soundSource.connect(this._inputAudioNode);
  59177. this._soundSource.loop = this.loop;
  59178. this._soundSource.playbackRate.value = this._playbackRate;
  59179. this._soundSource.onended = function () { _this._onended(); };
  59180. if (this._soundSource.buffer) {
  59181. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  59182. }
  59183. }
  59184. this._startTime = startTime;
  59185. this.isPlaying = true;
  59186. this.isPaused = false;
  59187. }
  59188. catch (ex) {
  59189. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  59190. }
  59191. }
  59192. };
  59193. Sound.prototype._onended = function () {
  59194. this.isPlaying = false;
  59195. if (this.onended) {
  59196. this.onended();
  59197. }
  59198. };
  59199. /**
  59200. * Stop the sound
  59201. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  59202. */
  59203. Sound.prototype.stop = function (time) {
  59204. if (this.isPlaying) {
  59205. if (this._streaming) {
  59206. this._htmlAudioElement.pause();
  59207. // Test needed for Firefox or it will generate an Invalid State Error
  59208. if (this._htmlAudioElement.currentTime > 0) {
  59209. this._htmlAudioElement.currentTime = 0;
  59210. }
  59211. }
  59212. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  59213. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  59214. this._soundSource.stop(stopTime);
  59215. this._soundSource.onended = function () { };
  59216. if (!this.isPaused) {
  59217. this._startOffset = 0;
  59218. }
  59219. }
  59220. this.isPlaying = false;
  59221. }
  59222. };
  59223. Sound.prototype.pause = function () {
  59224. if (this.isPlaying) {
  59225. this.isPaused = true;
  59226. if (this._streaming) {
  59227. this._htmlAudioElement.pause();
  59228. }
  59229. else if (BABYLON.Engine.audioEngine.audioContext) {
  59230. this.stop(0);
  59231. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  59232. }
  59233. }
  59234. };
  59235. Sound.prototype.setVolume = function (newVolume, time) {
  59236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  59237. if (time && BABYLON.Engine.audioEngine.audioContext) {
  59238. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  59239. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  59240. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  59241. }
  59242. else {
  59243. this._soundGain.gain.value = newVolume;
  59244. }
  59245. }
  59246. this._volume = newVolume;
  59247. };
  59248. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  59249. this._playbackRate = newPlaybackRate;
  59250. if (this.isPlaying) {
  59251. if (this._streaming) {
  59252. this._htmlAudioElement.playbackRate = this._playbackRate;
  59253. }
  59254. else if (this._soundSource) {
  59255. this._soundSource.playbackRate.value = this._playbackRate;
  59256. }
  59257. }
  59258. };
  59259. Sound.prototype.getVolume = function () {
  59260. return this._volume;
  59261. };
  59262. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  59263. var _this = this;
  59264. if (this._connectedMesh && this._registerFunc) {
  59265. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  59266. this._registerFunc = null;
  59267. }
  59268. this._connectedMesh = meshToConnectTo;
  59269. if (!this.spatialSound) {
  59270. this.spatialSound = true;
  59271. this._createSpatialParameters();
  59272. if (this.isPlaying && this.loop) {
  59273. this.stop();
  59274. this.play();
  59275. }
  59276. }
  59277. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  59278. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  59279. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  59280. };
  59281. Sound.prototype.detachFromMesh = function () {
  59282. if (this._connectedMesh && this._registerFunc) {
  59283. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  59284. this._registerFunc = null;
  59285. this._connectedMesh = null;
  59286. }
  59287. };
  59288. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  59289. if (!node.getBoundingInfo) {
  59290. return;
  59291. }
  59292. var mesh = node;
  59293. var boundingInfo = mesh.getBoundingInfo();
  59294. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  59295. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  59296. this._updateDirection();
  59297. }
  59298. };
  59299. Sound.prototype.clone = function () {
  59300. var _this = this;
  59301. if (!this._streaming) {
  59302. var setBufferAndRun = function () {
  59303. if (_this._isReadyToPlay) {
  59304. clonedSound._audioBuffer = _this.getAudioBuffer();
  59305. clonedSound._isReadyToPlay = true;
  59306. if (clonedSound.autoplay) {
  59307. clonedSound.play();
  59308. }
  59309. }
  59310. else {
  59311. window.setTimeout(setBufferAndRun, 300);
  59312. }
  59313. };
  59314. var currentOptions = {
  59315. autoplay: this.autoplay, loop: this.loop,
  59316. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  59317. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  59318. refDistance: this.refDistance, distanceModel: this.distanceModel
  59319. };
  59320. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  59321. if (this.useCustomAttenuation) {
  59322. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  59323. }
  59324. clonedSound.setPosition(this._position);
  59325. clonedSound.setPlaybackRate(this._playbackRate);
  59326. setBufferAndRun();
  59327. return clonedSound;
  59328. }
  59329. else {
  59330. return null;
  59331. }
  59332. };
  59333. Sound.prototype.getAudioBuffer = function () {
  59334. return this._audioBuffer;
  59335. };
  59336. Sound.prototype.serialize = function () {
  59337. var serializationObject = {
  59338. name: this.name,
  59339. url: this.name,
  59340. autoplay: this.autoplay,
  59341. loop: this.loop,
  59342. volume: this._volume,
  59343. spatialSound: this.spatialSound,
  59344. maxDistance: this.maxDistance,
  59345. rolloffFactor: this.rolloffFactor,
  59346. refDistance: this.refDistance,
  59347. distanceModel: this.distanceModel,
  59348. playbackRate: this._playbackRate,
  59349. panningModel: this._panningModel,
  59350. soundTrackId: this.soundTrackId
  59351. };
  59352. if (this.spatialSound) {
  59353. if (this._connectedMesh)
  59354. serializationObject.connectedMeshId = this._connectedMesh.id;
  59355. serializationObject.position = this._position.asArray();
  59356. serializationObject.refDistance = this.refDistance;
  59357. serializationObject.distanceModel = this.distanceModel;
  59358. serializationObject.isDirectional = this._isDirectional;
  59359. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  59360. serializationObject.coneInnerAngle = this._coneInnerAngle;
  59361. serializationObject.coneOuterAngle = this._coneOuterAngle;
  59362. serializationObject.coneOuterGain = this._coneOuterGain;
  59363. }
  59364. return serializationObject;
  59365. };
  59366. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  59367. var soundName = parsedSound.name;
  59368. var soundUrl;
  59369. if (parsedSound.url) {
  59370. soundUrl = rootUrl + parsedSound.url;
  59371. }
  59372. else {
  59373. soundUrl = rootUrl + soundName;
  59374. }
  59375. var options = {
  59376. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  59377. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  59378. rolloffFactor: parsedSound.rolloffFactor,
  59379. refDistance: parsedSound.refDistance,
  59380. distanceModel: parsedSound.distanceModel,
  59381. playbackRate: parsedSound.playbackRate
  59382. };
  59383. var newSound;
  59384. if (!sourceSound) {
  59385. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  59386. scene._addPendingData(newSound);
  59387. }
  59388. else {
  59389. var setBufferAndRun = function () {
  59390. if (sourceSound._isReadyToPlay) {
  59391. newSound._audioBuffer = sourceSound.getAudioBuffer();
  59392. newSound._isReadyToPlay = true;
  59393. if (newSound.autoplay) {
  59394. newSound.play();
  59395. }
  59396. }
  59397. else {
  59398. window.setTimeout(setBufferAndRun, 300);
  59399. }
  59400. };
  59401. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  59402. setBufferAndRun();
  59403. }
  59404. if (parsedSound.position) {
  59405. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  59406. newSound.setPosition(soundPosition);
  59407. }
  59408. if (parsedSound.isDirectional) {
  59409. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  59410. if (parsedSound.localDirectionToMesh) {
  59411. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  59412. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  59413. }
  59414. }
  59415. if (parsedSound.connectedMeshId) {
  59416. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  59417. if (connectedMesh) {
  59418. newSound.attachToMesh(connectedMesh);
  59419. }
  59420. }
  59421. return newSound;
  59422. };
  59423. return Sound;
  59424. }());
  59425. BABYLON.Sound = Sound;
  59426. })(BABYLON || (BABYLON = {}));
  59427. //# sourceMappingURL=babylon.sound.js.map
  59428. "use strict";
  59429. var BABYLON;
  59430. (function (BABYLON) {
  59431. var SoundTrack = /** @class */ (function () {
  59432. function SoundTrack(scene, options) {
  59433. this.id = -1;
  59434. this._isMainTrack = false;
  59435. this._isInitialized = false;
  59436. this._scene = scene;
  59437. this.soundCollection = new Array();
  59438. this._options = options;
  59439. if (!this._isMainTrack) {
  59440. this._scene.soundTracks.push(this);
  59441. this.id = this._scene.soundTracks.length - 1;
  59442. }
  59443. }
  59444. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  59445. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  59446. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  59447. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  59448. if (this._options) {
  59449. if (this._options.volume) {
  59450. this._outputAudioNode.gain.value = this._options.volume;
  59451. }
  59452. if (this._options.mainTrack) {
  59453. this._isMainTrack = this._options.mainTrack;
  59454. }
  59455. }
  59456. this._isInitialized = true;
  59457. }
  59458. };
  59459. SoundTrack.prototype.dispose = function () {
  59460. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  59461. if (this._connectedAnalyser) {
  59462. this._connectedAnalyser.stopDebugCanvas();
  59463. }
  59464. while (this.soundCollection.length) {
  59465. this.soundCollection[0].dispose();
  59466. }
  59467. if (this._outputAudioNode) {
  59468. this._outputAudioNode.disconnect();
  59469. }
  59470. this._outputAudioNode = null;
  59471. }
  59472. };
  59473. SoundTrack.prototype.AddSound = function (sound) {
  59474. if (!this._isInitialized) {
  59475. this._initializeSoundTrackAudioGraph();
  59476. }
  59477. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  59478. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  59479. }
  59480. if (sound.soundTrackId) {
  59481. if (sound.soundTrackId === -1) {
  59482. this._scene.mainSoundTrack.RemoveSound(sound);
  59483. }
  59484. else {
  59485. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  59486. }
  59487. }
  59488. this.soundCollection.push(sound);
  59489. sound.soundTrackId = this.id;
  59490. };
  59491. SoundTrack.prototype.RemoveSound = function (sound) {
  59492. var index = this.soundCollection.indexOf(sound);
  59493. if (index !== -1) {
  59494. this.soundCollection.splice(index, 1);
  59495. }
  59496. };
  59497. SoundTrack.prototype.setVolume = function (newVolume) {
  59498. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  59499. this._outputAudioNode.gain.value = newVolume;
  59500. }
  59501. };
  59502. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  59503. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59504. for (var i = 0; i < this.soundCollection.length; i++) {
  59505. this.soundCollection[i].switchPanningModelToHRTF();
  59506. }
  59507. }
  59508. };
  59509. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  59510. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  59511. for (var i = 0; i < this.soundCollection.length; i++) {
  59512. this.soundCollection[i].switchPanningModelToEqualPower();
  59513. }
  59514. }
  59515. };
  59516. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  59517. if (this._connectedAnalyser) {
  59518. this._connectedAnalyser.stopDebugCanvas();
  59519. }
  59520. this._connectedAnalyser = analyser;
  59521. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  59522. this._outputAudioNode.disconnect();
  59523. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  59524. }
  59525. };
  59526. return SoundTrack;
  59527. }());
  59528. BABYLON.SoundTrack = SoundTrack;
  59529. })(BABYLON || (BABYLON = {}));
  59530. //# sourceMappingURL=babylon.soundtrack.js.map
  59531. "use strict";
  59532. var BABYLON;
  59533. (function (BABYLON) {
  59534. var Analyser = /** @class */ (function () {
  59535. function Analyser(scene) {
  59536. this.SMOOTHING = 0.75;
  59537. this.FFT_SIZE = 512;
  59538. this.BARGRAPHAMPLITUDE = 256;
  59539. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  59540. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  59541. this._scene = scene;
  59542. this._audioEngine = BABYLON.Engine.audioEngine;
  59543. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  59544. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  59545. this._webAudioAnalyser.minDecibels = -140;
  59546. this._webAudioAnalyser.maxDecibels = 0;
  59547. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  59548. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  59549. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  59550. }
  59551. }
  59552. Analyser.prototype.getFrequencyBinCount = function () {
  59553. if (this._audioEngine.canUseWebAudio) {
  59554. return this._webAudioAnalyser.frequencyBinCount;
  59555. }
  59556. else {
  59557. return 0;
  59558. }
  59559. };
  59560. Analyser.prototype.getByteFrequencyData = function () {
  59561. if (this._audioEngine.canUseWebAudio) {
  59562. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  59563. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  59564. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  59565. }
  59566. return this._byteFreqs;
  59567. };
  59568. Analyser.prototype.getByteTimeDomainData = function () {
  59569. if (this._audioEngine.canUseWebAudio) {
  59570. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  59571. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  59572. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  59573. }
  59574. return this._byteTime;
  59575. };
  59576. Analyser.prototype.getFloatFrequencyData = function () {
  59577. if (this._audioEngine.canUseWebAudio) {
  59578. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  59579. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  59580. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  59581. }
  59582. return this._floatFreqs;
  59583. };
  59584. Analyser.prototype.drawDebugCanvas = function () {
  59585. var _this = this;
  59586. if (this._audioEngine.canUseWebAudio) {
  59587. if (!this._debugCanvas) {
  59588. this._debugCanvas = document.createElement("canvas");
  59589. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  59590. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  59591. this._debugCanvas.style.position = "absolute";
  59592. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  59593. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  59594. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  59595. document.body.appendChild(this._debugCanvas);
  59596. this._registerFunc = function () {
  59597. _this.drawDebugCanvas();
  59598. };
  59599. this._scene.registerBeforeRender(this._registerFunc);
  59600. }
  59601. if (this._registerFunc && this._debugCanvasContext) {
  59602. var workingArray = this.getByteFrequencyData();
  59603. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  59604. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  59605. // Draw the frequency domain chart.
  59606. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  59607. var value = workingArray[i];
  59608. var percent = value / this.BARGRAPHAMPLITUDE;
  59609. var height = this.DEBUGCANVASSIZE.height * percent;
  59610. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  59611. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  59612. var hue = i / this.getFrequencyBinCount() * 360;
  59613. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  59614. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  59615. }
  59616. }
  59617. }
  59618. };
  59619. Analyser.prototype.stopDebugCanvas = function () {
  59620. if (this._debugCanvas) {
  59621. if (this._registerFunc) {
  59622. this._scene.unregisterBeforeRender(this._registerFunc);
  59623. this._registerFunc = null;
  59624. }
  59625. document.body.removeChild(this._debugCanvas);
  59626. this._debugCanvas = null;
  59627. this._debugCanvasContext = null;
  59628. }
  59629. };
  59630. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  59631. if (this._audioEngine.canUseWebAudio) {
  59632. inputAudioNode.connect(this._webAudioAnalyser);
  59633. this._webAudioAnalyser.connect(outputAudioNode);
  59634. }
  59635. };
  59636. Analyser.prototype.dispose = function () {
  59637. if (this._audioEngine.canUseWebAudio) {
  59638. this._webAudioAnalyser.disconnect();
  59639. }
  59640. };
  59641. return Analyser;
  59642. }());
  59643. BABYLON.Analyser = Analyser;
  59644. })(BABYLON || (BABYLON = {}));
  59645. //# sourceMappingURL=babylon.analyser.js.map
  59646. "use strict";
  59647. var BABYLON;
  59648. (function (BABYLON) {
  59649. var CubeTexture = /** @class */ (function (_super) {
  59650. __extends(CubeTexture, _super);
  59651. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  59652. if (extensions === void 0) { extensions = null; }
  59653. if (noMipmap === void 0) { noMipmap = false; }
  59654. if (files === void 0) { files = null; }
  59655. if (onLoad === void 0) { onLoad = null; }
  59656. if (onError === void 0) { onError = null; }
  59657. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59658. if (prefiltered === void 0) { prefiltered = false; }
  59659. if (forcedExtension === void 0) { forcedExtension = null; }
  59660. var _this = _super.call(this, scene) || this;
  59661. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59662. /**
  59663. * Gets or sets the center of the bounding box associated with the cube texture
  59664. * It must define where the camera used to render the texture was set
  59665. */
  59666. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59667. _this.name = rootUrl;
  59668. _this.url = rootUrl;
  59669. _this._noMipmap = noMipmap;
  59670. _this.hasAlpha = false;
  59671. _this._format = format;
  59672. _this._prefiltered = prefiltered;
  59673. _this.isCube = true;
  59674. _this._textureMatrix = BABYLON.Matrix.Identity();
  59675. if (prefiltered) {
  59676. _this.gammaSpace = false;
  59677. }
  59678. if (!rootUrl && !files) {
  59679. return _this;
  59680. }
  59681. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  59682. var lastDot = rootUrl.lastIndexOf(".");
  59683. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  59684. var isDDS = (extension === ".dds");
  59685. if (!files) {
  59686. if (!isDDS && !extensions) {
  59687. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  59688. }
  59689. files = [];
  59690. if (extensions) {
  59691. for (var index = 0; index < extensions.length; index++) {
  59692. files.push(rootUrl + extensions[index]);
  59693. }
  59694. }
  59695. }
  59696. _this._files = files;
  59697. if (!_this._texture) {
  59698. if (!scene.useDelayedTextureLoading) {
  59699. if (prefiltered) {
  59700. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  59701. }
  59702. else {
  59703. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  59704. }
  59705. }
  59706. else {
  59707. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59708. }
  59709. }
  59710. else if (onLoad) {
  59711. if (_this._texture.isReady) {
  59712. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  59713. }
  59714. else {
  59715. _this._texture.onLoadedObservable.add(onLoad);
  59716. }
  59717. }
  59718. return _this;
  59719. }
  59720. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  59721. get: function () {
  59722. return this._boundingBoxSize;
  59723. },
  59724. /**
  59725. * Gets or sets the size of the bounding box associated with the cube texture
  59726. * When defined, the cubemap will switch to local mode
  59727. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59728. * @example https://www.babylonjs-playground.com/#RNASML
  59729. */
  59730. set: function (value) {
  59731. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59732. return;
  59733. }
  59734. this._boundingBoxSize = value;
  59735. var scene = this.getScene();
  59736. if (scene) {
  59737. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59738. }
  59739. },
  59740. enumerable: true,
  59741. configurable: true
  59742. });
  59743. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  59744. var rootUrlKey = "";
  59745. files.forEach(function (url) { return rootUrlKey += url; });
  59746. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  59747. };
  59748. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  59749. if (forcedExtension === void 0) { forcedExtension = null; }
  59750. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  59751. };
  59752. // Methods
  59753. CubeTexture.prototype.delayLoad = function () {
  59754. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59755. return;
  59756. }
  59757. var scene = this.getScene();
  59758. if (!scene) {
  59759. return;
  59760. }
  59761. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59762. this._texture = this._getFromCache(this.url, this._noMipmap);
  59763. if (!this._texture) {
  59764. if (this._prefiltered) {
  59765. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  59766. }
  59767. else {
  59768. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  59769. }
  59770. }
  59771. };
  59772. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  59773. return this._textureMatrix;
  59774. };
  59775. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  59776. this._textureMatrix = value;
  59777. };
  59778. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59779. var texture = BABYLON.SerializationHelper.Parse(function () {
  59780. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  59781. }, parsedTexture, scene);
  59782. // Local Cubemaps
  59783. if (parsedTexture.boundingBoxPosition) {
  59784. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59785. }
  59786. if (parsedTexture.boundingBoxSize) {
  59787. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59788. }
  59789. // Animations
  59790. if (parsedTexture.animations) {
  59791. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59792. var parsedAnimation = parsedTexture.animations[animationIndex];
  59793. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59794. }
  59795. }
  59796. return texture;
  59797. };
  59798. CubeTexture.prototype.clone = function () {
  59799. var _this = this;
  59800. return BABYLON.SerializationHelper.Clone(function () {
  59801. var scene = _this.getScene();
  59802. if (!scene) {
  59803. return _this;
  59804. }
  59805. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59806. }, this);
  59807. };
  59808. return CubeTexture;
  59809. }(BABYLON.BaseTexture));
  59810. BABYLON.CubeTexture = CubeTexture;
  59811. })(BABYLON || (BABYLON = {}));
  59812. //# sourceMappingURL=babylon.cubeTexture.js.map
  59813. "use strict";
  59814. var BABYLON;
  59815. (function (BABYLON) {
  59816. var RenderTargetTexture = /** @class */ (function (_super) {
  59817. __extends(RenderTargetTexture, _super);
  59818. /**
  59819. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59820. * or used a shadow, depth texture...
  59821. * @param name The friendly name of the texture
  59822. * @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)
  59823. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59824. * @param generateMipMaps True if mip maps need to be generated after render.
  59825. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59826. * @param type The type of the buffer in the RTT (int, half float, float...)
  59827. * @param isCube True if a cube texture needs to be created
  59828. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59829. * @param generateDepthBuffer True to generate a depth buffer
  59830. * @param generateStencilBuffer True to generate a stencil buffer
  59831. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59832. */
  59833. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59834. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59835. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59836. if (isCube === void 0) { isCube = false; }
  59837. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59838. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59839. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59840. if (isMulti === void 0) { isMulti = false; }
  59841. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59842. _this.isCube = isCube;
  59843. /**
  59844. * Use this list to define the list of mesh you want to render.
  59845. */
  59846. _this.renderList = new Array();
  59847. _this.renderParticles = true;
  59848. _this.renderSprites = false;
  59849. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59850. _this.ignoreCameraViewport = false;
  59851. // Events
  59852. /**
  59853. * An event triggered when the texture is unbind.
  59854. */
  59855. _this.onBeforeBindObservable = new BABYLON.Observable();
  59856. /**
  59857. * An event triggered when the texture is unbind.
  59858. */
  59859. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59860. /**
  59861. * An event triggered before rendering the texture
  59862. */
  59863. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59864. /**
  59865. * An event triggered after rendering the texture
  59866. */
  59867. _this.onAfterRenderObservable = new BABYLON.Observable();
  59868. /**
  59869. * An event triggered after the texture clear
  59870. */
  59871. _this.onClearObservable = new BABYLON.Observable();
  59872. _this._currentRefreshId = -1;
  59873. _this._refreshRate = 1;
  59874. _this._samples = 1;
  59875. /**
  59876. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59877. * It must define where the camera used to render the texture is set
  59878. */
  59879. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59880. scene = _this.getScene();
  59881. if (!scene) {
  59882. return _this;
  59883. }
  59884. _this._engine = scene.getEngine();
  59885. _this.name = name;
  59886. _this.isRenderTarget = true;
  59887. _this._initialSizeParameter = size;
  59888. _this._processSizeParameter(size);
  59889. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59890. });
  59891. _this._generateMipMaps = generateMipMaps ? true : false;
  59892. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59893. // Rendering groups
  59894. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59895. if (isMulti) {
  59896. return _this;
  59897. }
  59898. _this._renderTargetOptions = {
  59899. generateMipMaps: generateMipMaps,
  59900. type: type,
  59901. samplingMode: samplingMode,
  59902. generateDepthBuffer: generateDepthBuffer,
  59903. generateStencilBuffer: generateStencilBuffer
  59904. };
  59905. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59906. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59907. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59908. }
  59909. if (isCube) {
  59910. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59911. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59912. _this._textureMatrix = BABYLON.Matrix.Identity();
  59913. }
  59914. else {
  59915. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59916. }
  59917. return _this;
  59918. }
  59919. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59920. get: function () {
  59921. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59922. },
  59923. enumerable: true,
  59924. configurable: true
  59925. });
  59926. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59927. get: function () {
  59928. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59929. },
  59930. enumerable: true,
  59931. configurable: true
  59932. });
  59933. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59934. get: function () {
  59935. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59936. },
  59937. enumerable: true,
  59938. configurable: true
  59939. });
  59940. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59941. set: function (callback) {
  59942. if (this._onAfterUnbindObserver) {
  59943. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59944. }
  59945. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59946. },
  59947. enumerable: true,
  59948. configurable: true
  59949. });
  59950. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59951. set: function (callback) {
  59952. if (this._onBeforeRenderObserver) {
  59953. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59954. }
  59955. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59956. },
  59957. enumerable: true,
  59958. configurable: true
  59959. });
  59960. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59961. set: function (callback) {
  59962. if (this._onAfterRenderObserver) {
  59963. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59964. }
  59965. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59966. },
  59967. enumerable: true,
  59968. configurable: true
  59969. });
  59970. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59971. set: function (callback) {
  59972. if (this._onClearObserver) {
  59973. this.onClearObservable.remove(this._onClearObserver);
  59974. }
  59975. this._onClearObserver = this.onClearObservable.add(callback);
  59976. },
  59977. enumerable: true,
  59978. configurable: true
  59979. });
  59980. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59981. get: function () {
  59982. return this._renderTargetOptions;
  59983. },
  59984. enumerable: true,
  59985. configurable: true
  59986. });
  59987. RenderTargetTexture.prototype._onRatioRescale = function () {
  59988. if (this._sizeRatio) {
  59989. this.resize(this._initialSizeParameter);
  59990. }
  59991. };
  59992. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59993. get: function () {
  59994. return this._boundingBoxSize;
  59995. },
  59996. /**
  59997. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59998. * When defined, the cubemap will switch to local mode
  59999. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  60000. * @example https://www.babylonjs-playground.com/#RNASML
  60001. */
  60002. set: function (value) {
  60003. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  60004. return;
  60005. }
  60006. this._boundingBoxSize = value;
  60007. var scene = this.getScene();
  60008. if (scene) {
  60009. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  60010. }
  60011. },
  60012. enumerable: true,
  60013. configurable: true
  60014. });
  60015. /**
  60016. * Creates a depth stencil texture.
  60017. * This is only available in WebGL 2 or with the depth texture extension available.
  60018. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  60019. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  60020. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  60021. */
  60022. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  60023. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  60024. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  60025. if (generateStencil === void 0) { generateStencil = false; }
  60026. if (!this.getScene()) {
  60027. return;
  60028. }
  60029. var engine = this.getScene().getEngine();
  60030. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  60031. bilinearFiltering: bilinearFiltering,
  60032. comparisonFunction: comparisonFunction,
  60033. generateStencil: generateStencil,
  60034. isCube: this.isCube
  60035. });
  60036. engine.setFrameBufferDepthStencilTexture(this);
  60037. };
  60038. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  60039. if (size.ratio) {
  60040. this._sizeRatio = size.ratio;
  60041. this._size = {
  60042. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  60043. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  60044. };
  60045. }
  60046. else {
  60047. this._size = size;
  60048. }
  60049. };
  60050. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  60051. get: function () {
  60052. return this._samples;
  60053. },
  60054. set: function (value) {
  60055. if (this._samples === value) {
  60056. return;
  60057. }
  60058. var scene = this.getScene();
  60059. if (!scene) {
  60060. return;
  60061. }
  60062. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  60063. },
  60064. enumerable: true,
  60065. configurable: true
  60066. });
  60067. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  60068. this._currentRefreshId = -1;
  60069. };
  60070. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  60071. get: function () {
  60072. return this._refreshRate;
  60073. },
  60074. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  60075. set: function (value) {
  60076. this._refreshRate = value;
  60077. this.resetRefreshCounter();
  60078. },
  60079. enumerable: true,
  60080. configurable: true
  60081. });
  60082. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  60083. if (!this._postProcessManager) {
  60084. var scene = this.getScene();
  60085. if (!scene) {
  60086. return;
  60087. }
  60088. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  60089. this._postProcesses = new Array();
  60090. }
  60091. this._postProcesses.push(postProcess);
  60092. this._postProcesses[0].autoClear = false;
  60093. };
  60094. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  60095. if (!this._postProcesses) {
  60096. return;
  60097. }
  60098. if (dispose) {
  60099. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  60100. var postProcess = _a[_i];
  60101. postProcess.dispose();
  60102. }
  60103. }
  60104. this._postProcesses = [];
  60105. };
  60106. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  60107. if (!this._postProcesses) {
  60108. return;
  60109. }
  60110. var index = this._postProcesses.indexOf(postProcess);
  60111. if (index === -1) {
  60112. return;
  60113. }
  60114. this._postProcesses.splice(index, 1);
  60115. if (this._postProcesses.length > 0) {
  60116. this._postProcesses[0].autoClear = false;
  60117. }
  60118. };
  60119. RenderTargetTexture.prototype._shouldRender = function () {
  60120. if (this._currentRefreshId === -1) {
  60121. this._currentRefreshId = 1;
  60122. return true;
  60123. }
  60124. if (this.refreshRate === this._currentRefreshId) {
  60125. this._currentRefreshId = 1;
  60126. return true;
  60127. }
  60128. this._currentRefreshId++;
  60129. return false;
  60130. };
  60131. RenderTargetTexture.prototype.getRenderSize = function () {
  60132. if (this._size.width) {
  60133. return this._size.width;
  60134. }
  60135. return this._size;
  60136. };
  60137. RenderTargetTexture.prototype.getRenderWidth = function () {
  60138. if (this._size.width) {
  60139. return this._size.width;
  60140. }
  60141. return this._size;
  60142. };
  60143. RenderTargetTexture.prototype.getRenderHeight = function () {
  60144. if (this._size.width) {
  60145. return this._size.height;
  60146. }
  60147. return this._size;
  60148. };
  60149. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  60150. get: function () {
  60151. return true;
  60152. },
  60153. enumerable: true,
  60154. configurable: true
  60155. });
  60156. RenderTargetTexture.prototype.scale = function (ratio) {
  60157. var newSize = this.getRenderSize() * ratio;
  60158. this.resize(newSize);
  60159. };
  60160. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  60161. if (this.isCube) {
  60162. return this._textureMatrix;
  60163. }
  60164. return _super.prototype.getReflectionTextureMatrix.call(this);
  60165. };
  60166. RenderTargetTexture.prototype.resize = function (size) {
  60167. this.releaseInternalTexture();
  60168. var scene = this.getScene();
  60169. if (!scene) {
  60170. return;
  60171. }
  60172. this._processSizeParameter(size);
  60173. if (this.isCube) {
  60174. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  60175. }
  60176. else {
  60177. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  60178. }
  60179. };
  60180. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  60181. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  60182. if (dumpForDebug === void 0) { dumpForDebug = false; }
  60183. var scene = this.getScene();
  60184. if (!scene) {
  60185. return;
  60186. }
  60187. var engine = scene.getEngine();
  60188. if (this.useCameraPostProcesses !== undefined) {
  60189. useCameraPostProcess = this.useCameraPostProcesses;
  60190. }
  60191. if (this._waitingRenderList) {
  60192. this.renderList = [];
  60193. for (var index = 0; index < this._waitingRenderList.length; index++) {
  60194. var id = this._waitingRenderList[index];
  60195. var mesh_1 = scene.getMeshByID(id);
  60196. if (mesh_1) {
  60197. this.renderList.push(mesh_1);
  60198. }
  60199. }
  60200. delete this._waitingRenderList;
  60201. }
  60202. // Is predicate defined?
  60203. if (this.renderListPredicate) {
  60204. if (this.renderList) {
  60205. this.renderList.splice(0); // Clear previous renderList
  60206. }
  60207. else {
  60208. this.renderList = [];
  60209. }
  60210. var scene = this.getScene();
  60211. if (!scene) {
  60212. return;
  60213. }
  60214. var sceneMeshes = scene.meshes;
  60215. for (var index = 0; index < sceneMeshes.length; index++) {
  60216. var mesh = sceneMeshes[index];
  60217. if (this.renderListPredicate(mesh)) {
  60218. this.renderList.push(mesh);
  60219. }
  60220. }
  60221. }
  60222. this.onBeforeBindObservable.notifyObservers(this);
  60223. // Set custom projection.
  60224. // Needs to be before binding to prevent changing the aspect ratio.
  60225. var camera;
  60226. if (this.activeCamera) {
  60227. camera = this.activeCamera;
  60228. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  60229. if (this.activeCamera !== scene.activeCamera) {
  60230. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  60231. }
  60232. }
  60233. else {
  60234. camera = scene.activeCamera;
  60235. if (camera) {
  60236. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  60237. }
  60238. }
  60239. // Prepare renderingManager
  60240. this._renderingManager.reset();
  60241. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  60242. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  60243. var sceneRenderId = scene.getRenderId();
  60244. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  60245. var mesh = currentRenderList[meshIndex];
  60246. if (mesh) {
  60247. if (!mesh.isReady(this.refreshRate === 0)) {
  60248. this.resetRefreshCounter();
  60249. continue;
  60250. }
  60251. mesh._preActivateForIntermediateRendering(sceneRenderId);
  60252. var isMasked = void 0;
  60253. if (!this.renderList && camera) {
  60254. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  60255. }
  60256. else {
  60257. isMasked = false;
  60258. }
  60259. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  60260. mesh._activate(sceneRenderId);
  60261. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  60262. var subMesh = mesh.subMeshes[subIndex];
  60263. scene._activeIndices.addCount(subMesh.indexCount, false);
  60264. this._renderingManager.dispatch(subMesh, mesh);
  60265. }
  60266. }
  60267. }
  60268. }
  60269. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  60270. var particleSystem = scene.particleSystems[particleIndex];
  60271. var emitter = particleSystem.emitter;
  60272. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  60273. continue;
  60274. }
  60275. if (currentRenderList.indexOf(emitter) >= 0) {
  60276. this._renderingManager.dispatchParticles(particleSystem);
  60277. }
  60278. }
  60279. if (this.isCube) {
  60280. for (var face = 0; face < 6; face++) {
  60281. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  60282. scene.incrementRenderId();
  60283. scene.resetCachedMaterial();
  60284. }
  60285. }
  60286. else {
  60287. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  60288. }
  60289. this.onAfterUnbindObservable.notifyObservers(this);
  60290. if (scene.activeCamera) {
  60291. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  60292. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  60293. }
  60294. engine.setViewport(scene.activeCamera.viewport);
  60295. }
  60296. scene.resetCachedMaterial();
  60297. };
  60298. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  60299. var minimum = 128;
  60300. var x = renderDimension * scale;
  60301. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  60302. // Ensure we don't exceed the render dimension (while staying POT)
  60303. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  60304. };
  60305. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  60306. var _this = this;
  60307. if (!this._texture) {
  60308. return;
  60309. }
  60310. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  60311. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  60312. });
  60313. };
  60314. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  60315. var scene = this.getScene();
  60316. if (!scene) {
  60317. return;
  60318. }
  60319. var engine = scene.getEngine();
  60320. if (!this._texture) {
  60321. return;
  60322. }
  60323. // Bind
  60324. if (this._postProcessManager) {
  60325. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  60326. }
  60327. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  60328. if (this._texture) {
  60329. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  60330. }
  60331. }
  60332. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  60333. // Clear
  60334. if (this.onClearObservable.hasObservers()) {
  60335. this.onClearObservable.notifyObservers(engine);
  60336. }
  60337. else {
  60338. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  60339. }
  60340. if (!this._doNotChangeAspectRatio) {
  60341. scene.updateTransformMatrix(true);
  60342. }
  60343. // Render
  60344. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  60345. if (this._postProcessManager) {
  60346. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  60347. }
  60348. else if (useCameraPostProcess) {
  60349. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  60350. }
  60351. if (!this._doNotChangeAspectRatio) {
  60352. scene.updateTransformMatrix(true);
  60353. }
  60354. // Dump ?
  60355. if (dumpForDebug) {
  60356. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  60357. }
  60358. // Unbind
  60359. if (!this.isCube || faceIndex === 5) {
  60360. if (this.isCube) {
  60361. if (faceIndex === 5) {
  60362. engine.generateMipMapsForCubemap(this._texture);
  60363. }
  60364. }
  60365. this.unbindFrameBuffer(engine, faceIndex);
  60366. }
  60367. else {
  60368. this.onAfterRenderObservable.notifyObservers(faceIndex);
  60369. }
  60370. };
  60371. /**
  60372. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  60373. * This allowed control for front to back rendering or reversly depending of the special needs.
  60374. *
  60375. * @param renderingGroupId The rendering group id corresponding to its index
  60376. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  60377. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  60378. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  60379. */
  60380. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  60381. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  60382. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  60383. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  60384. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  60385. };
  60386. /**
  60387. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  60388. *
  60389. * @param renderingGroupId The rendering group id corresponding to its index
  60390. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  60391. */
  60392. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  60393. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  60394. };
  60395. RenderTargetTexture.prototype.clone = function () {
  60396. var textureSize = this.getSize();
  60397. 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);
  60398. // Base texture
  60399. newTexture.hasAlpha = this.hasAlpha;
  60400. newTexture.level = this.level;
  60401. // RenderTarget Texture
  60402. newTexture.coordinatesMode = this.coordinatesMode;
  60403. if (this.renderList) {
  60404. newTexture.renderList = this.renderList.slice(0);
  60405. }
  60406. return newTexture;
  60407. };
  60408. RenderTargetTexture.prototype.serialize = function () {
  60409. if (!this.name) {
  60410. return null;
  60411. }
  60412. var serializationObject = _super.prototype.serialize.call(this);
  60413. serializationObject.renderTargetSize = this.getRenderSize();
  60414. serializationObject.renderList = [];
  60415. if (this.renderList) {
  60416. for (var index = 0; index < this.renderList.length; index++) {
  60417. serializationObject.renderList.push(this.renderList[index].id);
  60418. }
  60419. }
  60420. return serializationObject;
  60421. };
  60422. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  60423. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  60424. var objBuffer = this.getInternalTexture();
  60425. var scene = this.getScene();
  60426. if (objBuffer && scene) {
  60427. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  60428. }
  60429. };
  60430. RenderTargetTexture.prototype.dispose = function () {
  60431. if (this._postProcessManager) {
  60432. this._postProcessManager.dispose();
  60433. this._postProcessManager = null;
  60434. }
  60435. this.clearPostProcesses(true);
  60436. if (this._resizeObserver) {
  60437. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  60438. this._resizeObserver = null;
  60439. }
  60440. this.renderList = null;
  60441. // Remove from custom render targets
  60442. var scene = this.getScene();
  60443. if (!scene) {
  60444. return;
  60445. }
  60446. var index = scene.customRenderTargets.indexOf(this);
  60447. if (index >= 0) {
  60448. scene.customRenderTargets.splice(index, 1);
  60449. }
  60450. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  60451. var camera = _a[_i];
  60452. index = camera.customRenderTargets.indexOf(this);
  60453. if (index >= 0) {
  60454. camera.customRenderTargets.splice(index, 1);
  60455. }
  60456. }
  60457. _super.prototype.dispose.call(this);
  60458. };
  60459. RenderTargetTexture.prototype._rebuild = function () {
  60460. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  60461. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  60462. }
  60463. if (this._postProcessManager) {
  60464. this._postProcessManager._rebuild();
  60465. }
  60466. };
  60467. /**
  60468. * Clear the info related to rendering groups preventing retention point in material dispose.
  60469. */
  60470. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  60471. if (this._renderingManager) {
  60472. this._renderingManager.freeRenderingGroups();
  60473. }
  60474. };
  60475. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  60476. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  60477. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  60478. return RenderTargetTexture;
  60479. }(BABYLON.Texture));
  60480. BABYLON.RenderTargetTexture = RenderTargetTexture;
  60481. })(BABYLON || (BABYLON = {}));
  60482. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  60483. "use strict";
  60484. var BABYLON;
  60485. (function (BABYLON) {
  60486. ;
  60487. var MultiRenderTarget = /** @class */ (function (_super) {
  60488. __extends(MultiRenderTarget, _super);
  60489. function MultiRenderTarget(name, size, count, scene, options) {
  60490. var _this = this;
  60491. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  60492. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  60493. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  60494. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  60495. _this._engine = scene.getEngine();
  60496. if (!_this.isSupported) {
  60497. _this.dispose();
  60498. return;
  60499. }
  60500. var types = [];
  60501. var samplingModes = [];
  60502. for (var i = 0; i < count; i++) {
  60503. if (options && options.types && options.types[i] !== undefined) {
  60504. types.push(options.types[i]);
  60505. }
  60506. else {
  60507. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60508. }
  60509. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  60510. samplingModes.push(options.samplingModes[i]);
  60511. }
  60512. else {
  60513. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60514. }
  60515. }
  60516. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  60517. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  60518. _this._size = size;
  60519. _this._multiRenderTargetOptions = {
  60520. samplingModes: samplingModes,
  60521. generateMipMaps: generateMipMaps,
  60522. generateDepthBuffer: generateDepthBuffer,
  60523. generateStencilBuffer: generateStencilBuffer,
  60524. generateDepthTexture: generateDepthTexture,
  60525. types: types,
  60526. textureCount: count
  60527. };
  60528. _this._createInternalTextures();
  60529. _this._createTextures();
  60530. return _this;
  60531. }
  60532. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  60533. get: function () {
  60534. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  60535. },
  60536. enumerable: true,
  60537. configurable: true
  60538. });
  60539. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  60540. get: function () {
  60541. return this._textures;
  60542. },
  60543. enumerable: true,
  60544. configurable: true
  60545. });
  60546. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  60547. get: function () {
  60548. return this._textures[this._textures.length - 1];
  60549. },
  60550. enumerable: true,
  60551. configurable: true
  60552. });
  60553. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  60554. set: function (wrap) {
  60555. if (this._textures) {
  60556. for (var i = 0; i < this._textures.length; i++) {
  60557. this._textures[i].wrapU = wrap;
  60558. }
  60559. }
  60560. },
  60561. enumerable: true,
  60562. configurable: true
  60563. });
  60564. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  60565. set: function (wrap) {
  60566. if (this._textures) {
  60567. for (var i = 0; i < this._textures.length; i++) {
  60568. this._textures[i].wrapV = wrap;
  60569. }
  60570. }
  60571. },
  60572. enumerable: true,
  60573. configurable: true
  60574. });
  60575. MultiRenderTarget.prototype._rebuild = function () {
  60576. this.releaseInternalTextures();
  60577. this._createInternalTextures();
  60578. for (var i = 0; i < this._internalTextures.length; i++) {
  60579. var texture = this._textures[i];
  60580. texture._texture = this._internalTextures[i];
  60581. }
  60582. // Keeps references to frame buffer and stencil/depth buffer
  60583. this._texture = this._internalTextures[0];
  60584. };
  60585. MultiRenderTarget.prototype._createInternalTextures = function () {
  60586. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  60587. };
  60588. MultiRenderTarget.prototype._createTextures = function () {
  60589. this._textures = [];
  60590. for (var i = 0; i < this._internalTextures.length; i++) {
  60591. var texture = new BABYLON.Texture(null, this.getScene());
  60592. texture._texture = this._internalTextures[i];
  60593. this._textures.push(texture);
  60594. }
  60595. // Keeps references to frame buffer and stencil/depth buffer
  60596. this._texture = this._internalTextures[0];
  60597. };
  60598. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  60599. get: function () {
  60600. return this._samples;
  60601. },
  60602. set: function (value) {
  60603. if (this._samples === value) {
  60604. return;
  60605. }
  60606. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  60607. },
  60608. enumerable: true,
  60609. configurable: true
  60610. });
  60611. MultiRenderTarget.prototype.resize = function (size) {
  60612. this.releaseInternalTextures();
  60613. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  60614. this._createInternalTextures();
  60615. };
  60616. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  60617. var _this = this;
  60618. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  60619. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  60620. });
  60621. };
  60622. MultiRenderTarget.prototype.dispose = function () {
  60623. this.releaseInternalTextures();
  60624. _super.prototype.dispose.call(this);
  60625. };
  60626. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  60627. if (!this._internalTextures) {
  60628. return;
  60629. }
  60630. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  60631. if (this._internalTextures[i] !== undefined) {
  60632. this._internalTextures[i].dispose();
  60633. this._internalTextures.splice(i, 1);
  60634. }
  60635. }
  60636. };
  60637. return MultiRenderTarget;
  60638. }(BABYLON.RenderTargetTexture));
  60639. BABYLON.MultiRenderTarget = MultiRenderTarget;
  60640. })(BABYLON || (BABYLON = {}));
  60641. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  60642. "use strict";
  60643. var BABYLON;
  60644. (function (BABYLON) {
  60645. var MirrorTexture = /** @class */ (function (_super) {
  60646. __extends(MirrorTexture, _super);
  60647. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  60648. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60650. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  60651. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  60652. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  60653. _this._transformMatrix = BABYLON.Matrix.Zero();
  60654. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  60655. _this._adaptiveBlurKernel = 0;
  60656. _this._blurKernelX = 0;
  60657. _this._blurKernelY = 0;
  60658. _this._blurRatio = 1.0;
  60659. _this.ignoreCameraViewport = true;
  60660. _this.onBeforeRenderObservable.add(function () {
  60661. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  60662. _this._savedViewMatrix = scene.getViewMatrix();
  60663. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  60664. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  60665. scene.clipPlane = _this.mirrorPlane;
  60666. scene.getEngine().cullBackFaces = false;
  60667. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  60668. });
  60669. _this.onAfterRenderObservable.add(function () {
  60670. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  60671. scene.getEngine().cullBackFaces = true;
  60672. scene._mirroredCameraPosition = null;
  60673. delete scene.clipPlane;
  60674. });
  60675. return _this;
  60676. }
  60677. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  60678. get: function () {
  60679. return this._blurRatio;
  60680. },
  60681. set: function (value) {
  60682. if (this._blurRatio === value) {
  60683. return;
  60684. }
  60685. this._blurRatio = value;
  60686. this._preparePostProcesses();
  60687. },
  60688. enumerable: true,
  60689. configurable: true
  60690. });
  60691. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  60692. set: function (value) {
  60693. this._adaptiveBlurKernel = value;
  60694. this._autoComputeBlurKernel();
  60695. },
  60696. enumerable: true,
  60697. configurable: true
  60698. });
  60699. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  60700. set: function (value) {
  60701. this.blurKernelX = value;
  60702. this.blurKernelY = value;
  60703. },
  60704. enumerable: true,
  60705. configurable: true
  60706. });
  60707. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  60708. get: function () {
  60709. return this._blurKernelX;
  60710. },
  60711. set: function (value) {
  60712. if (this._blurKernelX === value) {
  60713. return;
  60714. }
  60715. this._blurKernelX = value;
  60716. this._preparePostProcesses();
  60717. },
  60718. enumerable: true,
  60719. configurable: true
  60720. });
  60721. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  60722. get: function () {
  60723. return this._blurKernelY;
  60724. },
  60725. set: function (value) {
  60726. if (this._blurKernelY === value) {
  60727. return;
  60728. }
  60729. this._blurKernelY = value;
  60730. this._preparePostProcesses();
  60731. },
  60732. enumerable: true,
  60733. configurable: true
  60734. });
  60735. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  60736. var engine = this.getScene().getEngine();
  60737. var dw = this.getRenderWidth() / engine.getRenderWidth();
  60738. var dh = this.getRenderHeight() / engine.getRenderHeight();
  60739. this.blurKernelX = this._adaptiveBlurKernel * dw;
  60740. this.blurKernelY = this._adaptiveBlurKernel * dh;
  60741. };
  60742. MirrorTexture.prototype._onRatioRescale = function () {
  60743. if (this._sizeRatio) {
  60744. this.resize(this._initialSizeParameter);
  60745. if (!this._adaptiveBlurKernel) {
  60746. this._preparePostProcesses();
  60747. }
  60748. }
  60749. if (this._adaptiveBlurKernel) {
  60750. this._autoComputeBlurKernel();
  60751. }
  60752. };
  60753. MirrorTexture.prototype._preparePostProcesses = function () {
  60754. this.clearPostProcesses(true);
  60755. if (this._blurKernelX && this._blurKernelY) {
  60756. var engine = this.getScene().getEngine();
  60757. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60758. 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);
  60759. this._blurX.autoClear = false;
  60760. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  60761. this._blurX.inputTexture = this._texture;
  60762. }
  60763. else {
  60764. this._blurX.alwaysForcePOT = true;
  60765. }
  60766. 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);
  60767. this._blurY.autoClear = false;
  60768. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  60769. this.addPostProcess(this._blurX);
  60770. this.addPostProcess(this._blurY);
  60771. }
  60772. else {
  60773. if (this._blurY) {
  60774. this.removePostProcess(this._blurY);
  60775. this._blurY.dispose();
  60776. this._blurY = null;
  60777. }
  60778. if (this._blurX) {
  60779. this.removePostProcess(this._blurX);
  60780. this._blurX.dispose();
  60781. this._blurX = null;
  60782. }
  60783. }
  60784. };
  60785. MirrorTexture.prototype.clone = function () {
  60786. var scene = this.getScene();
  60787. if (!scene) {
  60788. return this;
  60789. }
  60790. var textureSize = this.getSize();
  60791. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60792. // Base texture
  60793. newTexture.hasAlpha = this.hasAlpha;
  60794. newTexture.level = this.level;
  60795. // Mirror Texture
  60796. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60797. if (this.renderList) {
  60798. newTexture.renderList = this.renderList.slice(0);
  60799. }
  60800. return newTexture;
  60801. };
  60802. MirrorTexture.prototype.serialize = function () {
  60803. if (!this.name) {
  60804. return null;
  60805. }
  60806. var serializationObject = _super.prototype.serialize.call(this);
  60807. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60808. return serializationObject;
  60809. };
  60810. return MirrorTexture;
  60811. }(BABYLON.RenderTargetTexture));
  60812. BABYLON.MirrorTexture = MirrorTexture;
  60813. })(BABYLON || (BABYLON = {}));
  60814. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60815. "use strict";
  60816. var BABYLON;
  60817. (function (BABYLON) {
  60818. /**
  60819. * Creates a refraction texture used by refraction channel of the standard material.
  60820. * @param name the texture name
  60821. * @param size size of the underlying texture
  60822. * @param scene root scene
  60823. */
  60824. var RefractionTexture = /** @class */ (function (_super) {
  60825. __extends(RefractionTexture, _super);
  60826. function RefractionTexture(name, size, scene, generateMipMaps) {
  60827. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60828. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60829. _this.depth = 2.0;
  60830. _this.onBeforeRenderObservable.add(function () {
  60831. scene.clipPlane = _this.refractionPlane;
  60832. });
  60833. _this.onAfterRenderObservable.add(function () {
  60834. delete scene.clipPlane;
  60835. });
  60836. return _this;
  60837. }
  60838. RefractionTexture.prototype.clone = function () {
  60839. var scene = this.getScene();
  60840. if (!scene) {
  60841. return this;
  60842. }
  60843. var textureSize = this.getSize();
  60844. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60845. // Base texture
  60846. newTexture.hasAlpha = this.hasAlpha;
  60847. newTexture.level = this.level;
  60848. // Refraction Texture
  60849. newTexture.refractionPlane = this.refractionPlane.clone();
  60850. if (this.renderList) {
  60851. newTexture.renderList = this.renderList.slice(0);
  60852. }
  60853. newTexture.depth = this.depth;
  60854. return newTexture;
  60855. };
  60856. RefractionTexture.prototype.serialize = function () {
  60857. if (!this.name) {
  60858. return null;
  60859. }
  60860. var serializationObject = _super.prototype.serialize.call(this);
  60861. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60862. serializationObject.depth = this.depth;
  60863. return serializationObject;
  60864. };
  60865. return RefractionTexture;
  60866. }(BABYLON.RenderTargetTexture));
  60867. BABYLON.RefractionTexture = RefractionTexture;
  60868. })(BABYLON || (BABYLON = {}));
  60869. //# sourceMappingURL=babylon.refractionTexture.js.map
  60870. "use strict";
  60871. var BABYLON;
  60872. (function (BABYLON) {
  60873. /**
  60874. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60875. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60876. */
  60877. var DynamicTexture = /** @class */ (function (_super) {
  60878. __extends(DynamicTexture, _super);
  60879. /**
  60880. * Creates a {BABYLON.DynamicTexture}
  60881. * @param name defines the name of the texture
  60882. * @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
  60883. * @param scene defines the scene where you want the texture
  60884. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60885. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60886. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60887. */
  60888. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60889. if (scene === void 0) { scene = null; }
  60890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60891. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60892. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60893. _this.name = name;
  60894. _this._engine = _this.getScene().getEngine();
  60895. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60896. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60897. _this._generateMipMaps = generateMipMaps;
  60898. if (options.getContext) {
  60899. _this._canvas = options;
  60900. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60901. }
  60902. else {
  60903. _this._canvas = document.createElement("canvas");
  60904. if (options.width) {
  60905. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60906. }
  60907. else {
  60908. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60909. }
  60910. }
  60911. var textureSize = _this.getSize();
  60912. _this._canvas.width = textureSize.width;
  60913. _this._canvas.height = textureSize.height;
  60914. _this._context = _this._canvas.getContext("2d");
  60915. return _this;
  60916. }
  60917. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60918. /**
  60919. * Gets the current state of canRescale
  60920. */
  60921. get: function () {
  60922. return true;
  60923. },
  60924. enumerable: true,
  60925. configurable: true
  60926. });
  60927. DynamicTexture.prototype._recreate = function (textureSize) {
  60928. this._canvas.width = textureSize.width;
  60929. this._canvas.height = textureSize.height;
  60930. this.releaseInternalTexture();
  60931. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60932. };
  60933. /**
  60934. * Scales the texture
  60935. * @param ratio the scale factor to apply to both width and height
  60936. */
  60937. DynamicTexture.prototype.scale = function (ratio) {
  60938. var textureSize = this.getSize();
  60939. textureSize.width *= ratio;
  60940. textureSize.height *= ratio;
  60941. this._recreate(textureSize);
  60942. };
  60943. /**
  60944. * Resizes the texture
  60945. * @param width the new width
  60946. * @param height the new height
  60947. */
  60948. DynamicTexture.prototype.scaleTo = function (width, height) {
  60949. var textureSize = this.getSize();
  60950. textureSize.width = width;
  60951. textureSize.height = height;
  60952. this._recreate(textureSize);
  60953. };
  60954. /**
  60955. * Gets the context of the canvas used by the texture
  60956. * @returns the canvas context of the dynamic texture
  60957. */
  60958. DynamicTexture.prototype.getContext = function () {
  60959. return this._context;
  60960. };
  60961. /**
  60962. * Clears the texture
  60963. */
  60964. DynamicTexture.prototype.clear = function () {
  60965. var size = this.getSize();
  60966. this._context.fillRect(0, 0, size.width, size.height);
  60967. };
  60968. /**
  60969. * Updates the texture
  60970. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60971. */
  60972. DynamicTexture.prototype.update = function (invertY) {
  60973. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60974. };
  60975. /**
  60976. * Draws text onto the texture
  60977. * @param text defines the text to be drawn
  60978. * @param x defines the placement of the text from the left
  60979. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60980. * @param font defines the font to be used with font-style, font-size, font-name
  60981. * @param color defines the color used for the text
  60982. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60983. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60984. * @param update defines whether texture is immediately update (default is true)
  60985. */
  60986. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60987. if (update === void 0) { update = true; }
  60988. var size = this.getSize();
  60989. if (clearColor) {
  60990. this._context.fillStyle = clearColor;
  60991. this._context.fillRect(0, 0, size.width, size.height);
  60992. }
  60993. this._context.font = font;
  60994. if (x === null || x === undefined) {
  60995. var textSize = this._context.measureText(text);
  60996. x = (size.width - textSize.width) / 2;
  60997. }
  60998. if (y === null || y === undefined) {
  60999. var fontSize = parseInt((font.replace(/\D/g, '')));
  61000. ;
  61001. y = (size.height / 2) + (fontSize / 3.65);
  61002. }
  61003. this._context.fillStyle = color;
  61004. this._context.fillText(text, x, y);
  61005. if (update) {
  61006. this.update(invertY);
  61007. }
  61008. };
  61009. /**
  61010. * Clones the texture
  61011. * @returns the clone of the texture.
  61012. */
  61013. DynamicTexture.prototype.clone = function () {
  61014. var scene = this.getScene();
  61015. if (!scene) {
  61016. return this;
  61017. }
  61018. var textureSize = this.getSize();
  61019. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  61020. // Base texture
  61021. newTexture.hasAlpha = this.hasAlpha;
  61022. newTexture.level = this.level;
  61023. // Dynamic Texture
  61024. newTexture.wrapU = this.wrapU;
  61025. newTexture.wrapV = this.wrapV;
  61026. return newTexture;
  61027. };
  61028. /** @ignore */
  61029. DynamicTexture.prototype._rebuild = function () {
  61030. this.update();
  61031. };
  61032. return DynamicTexture;
  61033. }(BABYLON.Texture));
  61034. BABYLON.DynamicTexture = DynamicTexture;
  61035. })(BABYLON || (BABYLON = {}));
  61036. //# sourceMappingURL=babylon.dynamicTexture.js.map
  61037. "use strict";
  61038. var BABYLON;
  61039. (function (BABYLON) {
  61040. var VideoTexture = /** @class */ (function (_super) {
  61041. __extends(VideoTexture, _super);
  61042. /**
  61043. * Creates a video texture.
  61044. * Sample : https://doc.babylonjs.com/how_to/video_texture
  61045. * @param {string | null} name optional name, will detect from video source, if not defined
  61046. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  61047. * @param {BABYLON.Scene} scene is obviously the current scene.
  61048. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  61049. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  61050. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  61051. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  61052. */
  61053. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  61054. if (generateMipMaps === void 0) { generateMipMaps = false; }
  61055. if (invertY === void 0) { invertY = false; }
  61056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61057. if (settings === void 0) { settings = {
  61058. autoPlay: true,
  61059. loop: true,
  61060. autoUpdateTexture: true,
  61061. }; }
  61062. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  61063. _this._createInternalTexture = function () {
  61064. if (_this._texture != null) {
  61065. return;
  61066. }
  61067. if (!_this._engine.needPOTTextures ||
  61068. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  61069. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61070. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61071. }
  61072. else {
  61073. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61074. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61075. _this._generateMipMaps = false;
  61076. }
  61077. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  61078. _this._texture.isReady = true;
  61079. _this._updateInternalTexture();
  61080. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  61081. _this.onLoadObservable.notifyObservers(_this);
  61082. }
  61083. };
  61084. _this.reset = function () {
  61085. if (_this._texture == null) {
  61086. return;
  61087. }
  61088. _this._texture.dispose();
  61089. _this._texture = null;
  61090. };
  61091. _this._updateInternalTexture = function (e) {
  61092. if (_this._texture == null || !_this._texture.isReady) {
  61093. return;
  61094. }
  61095. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  61096. return;
  61097. }
  61098. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  61099. };
  61100. _this._engine = _this.getScene().getEngine();
  61101. _this._generateMipMaps = generateMipMaps;
  61102. _this._samplingMode = samplingMode;
  61103. _this.autoUpdateTexture = settings.autoUpdateTexture;
  61104. _this.name = name || _this._getName(src);
  61105. _this.video = _this._getVideo(src);
  61106. if (settings.autoPlay !== undefined) {
  61107. _this.video.autoplay = settings.autoPlay;
  61108. }
  61109. if (settings.loop !== undefined) {
  61110. _this.video.loop = settings.loop;
  61111. }
  61112. _this.video.addEventListener("canplay", _this._createInternalTexture);
  61113. _this.video.addEventListener("paused", _this._updateInternalTexture);
  61114. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  61115. _this.video.addEventListener("emptied", _this.reset);
  61116. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  61117. _this._createInternalTexture();
  61118. }
  61119. return _this;
  61120. }
  61121. VideoTexture.prototype._getName = function (src) {
  61122. if (src instanceof HTMLVideoElement) {
  61123. return src.currentSrc;
  61124. }
  61125. if (typeof src === "object") {
  61126. return src.toString();
  61127. }
  61128. return src;
  61129. };
  61130. ;
  61131. VideoTexture.prototype._getVideo = function (src) {
  61132. if (src instanceof HTMLVideoElement) {
  61133. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  61134. return src;
  61135. }
  61136. var video = document.createElement("video");
  61137. if (typeof src === "string") {
  61138. BABYLON.Tools.SetCorsBehavior(src, video);
  61139. video.src = src;
  61140. }
  61141. else {
  61142. BABYLON.Tools.SetCorsBehavior(src[0], video);
  61143. src.forEach(function (url) {
  61144. var source = document.createElement("source");
  61145. source.src = url;
  61146. video.appendChild(source);
  61147. });
  61148. }
  61149. return video;
  61150. };
  61151. ;
  61152. /**
  61153. * Internal method to initiate `update`.
  61154. */
  61155. VideoTexture.prototype._rebuild = function () {
  61156. this.update();
  61157. };
  61158. /**
  61159. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  61160. */
  61161. VideoTexture.prototype.update = function () {
  61162. if (!this.autoUpdateTexture) {
  61163. // Expecting user to call `updateTexture` manually
  61164. return;
  61165. }
  61166. this.updateTexture(true);
  61167. };
  61168. /**
  61169. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  61170. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  61171. */
  61172. VideoTexture.prototype.updateTexture = function (isVisible) {
  61173. if (!isVisible) {
  61174. return;
  61175. }
  61176. if (this.video.paused) {
  61177. return;
  61178. }
  61179. this._updateInternalTexture();
  61180. };
  61181. /**
  61182. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  61183. * @param url New url.
  61184. */
  61185. VideoTexture.prototype.updateURL = function (url) {
  61186. this.video.src = url;
  61187. };
  61188. VideoTexture.prototype.dispose = function () {
  61189. _super.prototype.dispose.call(this);
  61190. this.video.removeEventListener("canplay", this._createInternalTexture);
  61191. this.video.removeEventListener("paused", this._updateInternalTexture);
  61192. this.video.removeEventListener("seeked", this._updateInternalTexture);
  61193. this.video.removeEventListener("emptied", this.reset);
  61194. this.video.pause();
  61195. };
  61196. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  61197. var video = document.createElement("video");
  61198. var constraintsDeviceId;
  61199. if (constraints && constraints.deviceId) {
  61200. constraintsDeviceId = {
  61201. exact: constraints.deviceId,
  61202. };
  61203. }
  61204. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  61205. if (navigator.mediaDevices) {
  61206. navigator.mediaDevices.getUserMedia({ video: constraints })
  61207. .then(function (stream) {
  61208. if (video.mozSrcObject !== undefined) {
  61209. // hack for Firefox < 19
  61210. video.mozSrcObject = stream;
  61211. }
  61212. else {
  61213. video.srcObject = stream;
  61214. }
  61215. var onPlaying = function () {
  61216. if (onReady) {
  61217. onReady(new VideoTexture("video", video, scene, true, true));
  61218. }
  61219. video.removeEventListener("playing", onPlaying);
  61220. };
  61221. video.addEventListener("playing", onPlaying);
  61222. video.play();
  61223. })
  61224. .catch(function (err) {
  61225. BABYLON.Tools.Error(err.name);
  61226. });
  61227. }
  61228. else {
  61229. navigator.getUserMedia =
  61230. navigator.getUserMedia ||
  61231. navigator.webkitGetUserMedia ||
  61232. navigator.mozGetUserMedia ||
  61233. navigator.msGetUserMedia;
  61234. if (navigator.getUserMedia) {
  61235. navigator.getUserMedia({
  61236. video: {
  61237. deviceId: constraintsDeviceId,
  61238. width: {
  61239. min: (constraints && constraints.minWidth) || 256,
  61240. max: (constraints && constraints.maxWidth) || 640,
  61241. },
  61242. height: {
  61243. min: (constraints && constraints.minHeight) || 256,
  61244. max: (constraints && constraints.maxHeight) || 480,
  61245. },
  61246. },
  61247. }, function (stream) {
  61248. if (video.mozSrcObject !== undefined) {
  61249. // hack for Firefox < 19
  61250. video.mozSrcObject = stream;
  61251. }
  61252. else {
  61253. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  61254. }
  61255. video.play();
  61256. if (onReady) {
  61257. onReady(new VideoTexture("video", video, scene, true, true));
  61258. }
  61259. }, function (e) {
  61260. BABYLON.Tools.Error(e.name);
  61261. });
  61262. }
  61263. }
  61264. };
  61265. return VideoTexture;
  61266. }(BABYLON.Texture));
  61267. BABYLON.VideoTexture = VideoTexture;
  61268. })(BABYLON || (BABYLON = {}));
  61269. //# sourceMappingURL=babylon.videoTexture.js.map
  61270. "use strict";
  61271. var BABYLON;
  61272. (function (BABYLON) {
  61273. var RawTexture = /** @class */ (function (_super) {
  61274. __extends(RawTexture, _super);
  61275. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  61276. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61277. if (invertY === void 0) { invertY = false; }
  61278. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61279. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61280. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  61281. _this.format = format;
  61282. _this._engine = scene.getEngine();
  61283. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  61284. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61285. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61286. return _this;
  61287. }
  61288. RawTexture.prototype.update = function (data) {
  61289. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  61290. };
  61291. // Statics
  61292. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  61293. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61294. if (invertY === void 0) { invertY = false; }
  61295. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61296. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  61297. };
  61298. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  61299. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61300. if (invertY === void 0) { invertY = false; }
  61301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61302. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  61303. };
  61304. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  61305. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61306. if (invertY === void 0) { invertY = false; }
  61307. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61308. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  61309. };
  61310. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  61311. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61312. if (invertY === void 0) { invertY = false; }
  61313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61314. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61315. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  61316. };
  61317. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  61318. if (generateMipMaps === void 0) { generateMipMaps = true; }
  61319. if (invertY === void 0) { invertY = false; }
  61320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61321. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61322. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  61323. };
  61324. return RawTexture;
  61325. }(BABYLON.Texture));
  61326. BABYLON.RawTexture = RawTexture;
  61327. })(BABYLON || (BABYLON = {}));
  61328. //# sourceMappingURL=babylon.rawTexture.js.map
  61329. "use strict";
  61330. var BABYLON;
  61331. (function (BABYLON) {
  61332. /**
  61333. * PostProcess can be used to apply a shader to a texture after it has been rendered
  61334. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  61335. */
  61336. var PostProcess = /** @class */ (function () {
  61337. /**
  61338. * Creates a new instance PostProcess
  61339. * @param name The name of the PostProcess.
  61340. * @param fragmentUrl The url of the fragment shader to be used.
  61341. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  61342. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  61343. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  61344. * @param camera The camera to apply the render pass to.
  61345. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  61346. * @param engine The engine which the post process will be applied. (default: current engine)
  61347. * @param reusable If the post process can be reused on the same frame. (default: false)
  61348. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  61349. * @param textureType Type of textures used when performing the post process. (default: 0)
  61350. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  61351. * @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
  61352. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  61353. */
  61354. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  61355. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  61356. if (defines === void 0) { defines = null; }
  61357. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61358. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  61359. if (blockCompilation === void 0) { blockCompilation = false; }
  61360. this.name = name;
  61361. /**
  61362. * Width of the texture to apply the post process on
  61363. */
  61364. this.width = -1;
  61365. /**
  61366. * Height of the texture to apply the post process on
  61367. */
  61368. this.height = -1;
  61369. /**
  61370. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  61371. */
  61372. this._outputTexture = null;
  61373. /**
  61374. * If the buffer needs to be cleared before applying the post process. (default: true)
  61375. * Should be set to false if shader will overwrite all previous pixels.
  61376. */
  61377. this.autoClear = true;
  61378. /**
  61379. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  61380. */
  61381. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  61382. /**
  61383. * Animations to be used for the post processing
  61384. */
  61385. this.animations = new Array();
  61386. /**
  61387. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  61388. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  61389. */
  61390. this.enablePixelPerfectMode = false;
  61391. /**
  61392. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  61393. */
  61394. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  61395. /**
  61396. * Force textures to be a power of two (default: false)
  61397. */
  61398. this.alwaysForcePOT = false;
  61399. /**
  61400. * Number of sample textures (default: 1)
  61401. */
  61402. this.samples = 1;
  61403. /**
  61404. * Modify the scale of the post process to be the same as the viewport (default: false)
  61405. */
  61406. this.adaptScaleToCurrentViewport = false;
  61407. this._reusable = false;
  61408. /**
  61409. * Smart array of input and output textures for the post process.
  61410. */
  61411. this._textures = new BABYLON.SmartArray(2);
  61412. /**
  61413. * The index in _textures that corresponds to the output texture.
  61414. */
  61415. this._currentRenderTextureInd = 0;
  61416. this._scaleRatio = new BABYLON.Vector2(1, 1);
  61417. this._texelSize = BABYLON.Vector2.Zero();
  61418. // Events
  61419. /**
  61420. * An event triggered when the postprocess is activated.
  61421. */
  61422. this.onActivateObservable = new BABYLON.Observable();
  61423. /**
  61424. * An event triggered when the postprocess changes its size.
  61425. */
  61426. this.onSizeChangedObservable = new BABYLON.Observable();
  61427. /**
  61428. * An event triggered when the postprocess applies its effect.
  61429. */
  61430. this.onApplyObservable = new BABYLON.Observable();
  61431. /**
  61432. * An event triggered before rendering the postprocess
  61433. */
  61434. this.onBeforeRenderObservable = new BABYLON.Observable();
  61435. /**
  61436. * An event triggered after rendering the postprocess
  61437. */
  61438. this.onAfterRenderObservable = new BABYLON.Observable();
  61439. if (camera != null) {
  61440. this._camera = camera;
  61441. this._scene = camera.getScene();
  61442. camera.attachPostProcess(this);
  61443. this._engine = this._scene.getEngine();
  61444. this._scene.postProcesses.push(this);
  61445. }
  61446. else if (engine) {
  61447. this._engine = engine;
  61448. this._engine.postProcesses.push(this);
  61449. }
  61450. this._options = options;
  61451. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  61452. this._reusable = reusable || false;
  61453. this._textureType = textureType;
  61454. this._samplers = samplers || [];
  61455. this._samplers.push("textureSampler");
  61456. this._fragmentUrl = fragmentUrl;
  61457. this._vertexUrl = vertexUrl;
  61458. this._parameters = parameters || [];
  61459. this._parameters.push("scale");
  61460. this._indexParameters = indexParameters;
  61461. if (!blockCompilation) {
  61462. this.updateEffect(defines);
  61463. }
  61464. }
  61465. Object.defineProperty(PostProcess.prototype, "onActivate", {
  61466. /**
  61467. * A function that is added to the onActivateObservable
  61468. */
  61469. set: function (callback) {
  61470. if (this._onActivateObserver) {
  61471. this.onActivateObservable.remove(this._onActivateObserver);
  61472. }
  61473. if (callback) {
  61474. this._onActivateObserver = this.onActivateObservable.add(callback);
  61475. }
  61476. },
  61477. enumerable: true,
  61478. configurable: true
  61479. });
  61480. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  61481. /**
  61482. * A function that is added to the onSizeChangedObservable
  61483. */
  61484. set: function (callback) {
  61485. if (this._onSizeChangedObserver) {
  61486. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  61487. }
  61488. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  61489. },
  61490. enumerable: true,
  61491. configurable: true
  61492. });
  61493. Object.defineProperty(PostProcess.prototype, "onApply", {
  61494. /**
  61495. * A function that is added to the onApplyObservable
  61496. */
  61497. set: function (callback) {
  61498. if (this._onApplyObserver) {
  61499. this.onApplyObservable.remove(this._onApplyObserver);
  61500. }
  61501. this._onApplyObserver = this.onApplyObservable.add(callback);
  61502. },
  61503. enumerable: true,
  61504. configurable: true
  61505. });
  61506. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  61507. /**
  61508. * A function that is added to the onBeforeRenderObservable
  61509. */
  61510. set: function (callback) {
  61511. if (this._onBeforeRenderObserver) {
  61512. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  61513. }
  61514. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  61515. },
  61516. enumerable: true,
  61517. configurable: true
  61518. });
  61519. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  61520. /**
  61521. * A function that is added to the onAfterRenderObservable
  61522. */
  61523. set: function (callback) {
  61524. if (this._onAfterRenderObserver) {
  61525. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  61526. }
  61527. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  61528. },
  61529. enumerable: true,
  61530. configurable: true
  61531. });
  61532. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  61533. /**
  61534. * 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
  61535. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  61536. */
  61537. get: function () {
  61538. return this._textures.data[this._currentRenderTextureInd];
  61539. },
  61540. set: function (value) {
  61541. this._forcedOutputTexture = value;
  61542. },
  61543. enumerable: true,
  61544. configurable: true
  61545. });
  61546. /**
  61547. * Gets the camera which post process is applied to.
  61548. * @returns The camera the post process is applied to.
  61549. */
  61550. PostProcess.prototype.getCamera = function () {
  61551. return this._camera;
  61552. };
  61553. Object.defineProperty(PostProcess.prototype, "texelSize", {
  61554. /**
  61555. * Gets the texel size of the postprocess.
  61556. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  61557. */
  61558. get: function () {
  61559. if (this._shareOutputWithPostProcess) {
  61560. return this._shareOutputWithPostProcess.texelSize;
  61561. }
  61562. if (this._forcedOutputTexture) {
  61563. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  61564. }
  61565. return this._texelSize;
  61566. },
  61567. enumerable: true,
  61568. configurable: true
  61569. });
  61570. /**
  61571. * Gets the engine which this post process belongs to.
  61572. * @returns The engine the post process was enabled with.
  61573. */
  61574. PostProcess.prototype.getEngine = function () {
  61575. return this._engine;
  61576. };
  61577. /**
  61578. * The effect that is created when initializing the post process.
  61579. * @returns The created effect corrisponding the the postprocess.
  61580. */
  61581. PostProcess.prototype.getEffect = function () {
  61582. return this._effect;
  61583. };
  61584. /**
  61585. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  61586. * @param postProcess The post process to share the output with.
  61587. * @returns This post process.
  61588. */
  61589. PostProcess.prototype.shareOutputWith = function (postProcess) {
  61590. this._disposeTextures();
  61591. this._shareOutputWithPostProcess = postProcess;
  61592. return this;
  61593. };
  61594. /**
  61595. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  61596. * This should be called if the post process that shares output with this post process is disabled/disposed.
  61597. */
  61598. PostProcess.prototype.useOwnOutput = function () {
  61599. if (this._textures.length == 0) {
  61600. this._textures = new BABYLON.SmartArray(2);
  61601. }
  61602. this._shareOutputWithPostProcess = null;
  61603. };
  61604. /**
  61605. * Updates the effect with the current post process compile time values and recompiles the shader.
  61606. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  61607. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  61608. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  61609. * @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
  61610. * @param onCompiled Called when the shader has been compiled.
  61611. * @param onError Called if there is an error when compiling a shader.
  61612. */
  61613. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  61614. if (defines === void 0) { defines = null; }
  61615. if (uniforms === void 0) { uniforms = null; }
  61616. if (samplers === void 0) { samplers = null; }
  61617. 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);
  61618. };
  61619. /**
  61620. * The post process is reusable if it can be used multiple times within one frame.
  61621. * @returns If the post process is reusable
  61622. */
  61623. PostProcess.prototype.isReusable = function () {
  61624. return this._reusable;
  61625. };
  61626. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  61627. PostProcess.prototype.markTextureDirty = function () {
  61628. this.width = -1;
  61629. };
  61630. /**
  61631. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  61632. * 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.
  61633. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  61634. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  61635. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  61636. * @returns The target texture that was bound to be written to.
  61637. */
  61638. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  61639. var _this = this;
  61640. if (sourceTexture === void 0) { sourceTexture = null; }
  61641. camera = camera || this._camera;
  61642. var scene = camera.getScene();
  61643. var engine = scene.getEngine();
  61644. var maxSize = engine.getCaps().maxTextureSize;
  61645. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  61646. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  61647. // 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
  61648. var webVRCamera = camera.parent;
  61649. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  61650. requiredWidth /= 2;
  61651. }
  61652. var desiredWidth = (this._options.width || requiredWidth);
  61653. var desiredHeight = this._options.height || requiredHeight;
  61654. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  61655. if (this.adaptScaleToCurrentViewport) {
  61656. var currentViewport = engine.currentViewport;
  61657. if (currentViewport) {
  61658. desiredWidth *= currentViewport.width;
  61659. desiredHeight *= currentViewport.height;
  61660. }
  61661. }
  61662. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  61663. if (!this._options.width) {
  61664. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  61665. }
  61666. if (!this._options.height) {
  61667. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  61668. }
  61669. }
  61670. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  61671. if (this._textures.length > 0) {
  61672. for (var i = 0; i < this._textures.length; i++) {
  61673. this._engine._releaseTexture(this._textures.data[i]);
  61674. }
  61675. this._textures.reset();
  61676. }
  61677. this.width = desiredWidth;
  61678. this.height = desiredHeight;
  61679. var textureSize = { width: this.width, height: this.height };
  61680. var textureOptions = {
  61681. generateMipMaps: false,
  61682. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  61683. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  61684. samplingMode: this.renderTargetSamplingMode,
  61685. type: this._textureType
  61686. };
  61687. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61688. if (this._reusable) {
  61689. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  61690. }
  61691. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  61692. this.onSizeChangedObservable.notifyObservers(this);
  61693. }
  61694. this._textures.forEach(function (texture) {
  61695. if (texture.samples !== _this.samples) {
  61696. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  61697. }
  61698. });
  61699. }
  61700. var target;
  61701. if (this._shareOutputWithPostProcess) {
  61702. target = this._shareOutputWithPostProcess.inputTexture;
  61703. }
  61704. else if (this._forcedOutputTexture) {
  61705. target = this._forcedOutputTexture;
  61706. this.width = this._forcedOutputTexture.width;
  61707. this.height = this._forcedOutputTexture.height;
  61708. }
  61709. else {
  61710. target = this.inputTexture;
  61711. }
  61712. // Bind the input of this post process to be used as the output of the previous post process.
  61713. if (this.enablePixelPerfectMode) {
  61714. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  61715. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  61716. }
  61717. else {
  61718. this._scaleRatio.copyFromFloats(1, 1);
  61719. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  61720. }
  61721. this.onActivateObservable.notifyObservers(camera);
  61722. // Clear
  61723. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  61724. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  61725. }
  61726. if (this._reusable) {
  61727. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  61728. }
  61729. return target;
  61730. };
  61731. Object.defineProperty(PostProcess.prototype, "isSupported", {
  61732. /**
  61733. * If the post process is supported.
  61734. */
  61735. get: function () {
  61736. return this._effect.isSupported;
  61737. },
  61738. enumerable: true,
  61739. configurable: true
  61740. });
  61741. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  61742. /**
  61743. * The aspect ratio of the output texture.
  61744. */
  61745. get: function () {
  61746. if (this._shareOutputWithPostProcess) {
  61747. return this._shareOutputWithPostProcess.aspectRatio;
  61748. }
  61749. if (this._forcedOutputTexture) {
  61750. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  61751. }
  61752. return this.width / this.height;
  61753. },
  61754. enumerable: true,
  61755. configurable: true
  61756. });
  61757. /**
  61758. * Get a value indicating if the post-process is ready to be used
  61759. * @returns true if the post-process is ready (shader is compiled)
  61760. */
  61761. PostProcess.prototype.isReady = function () {
  61762. return this._effect && this._effect.isReady();
  61763. };
  61764. /**
  61765. * Binds all textures and uniforms to the shader, this will be run on every pass.
  61766. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  61767. */
  61768. PostProcess.prototype.apply = function () {
  61769. // Check
  61770. if (!this._effect || !this._effect.isReady())
  61771. return null;
  61772. // States
  61773. this._engine.enableEffect(this._effect);
  61774. this._engine.setState(false);
  61775. this._engine.setDepthBuffer(false);
  61776. this._engine.setDepthWrite(false);
  61777. // Alpha
  61778. this._engine.setAlphaMode(this.alphaMode);
  61779. if (this.alphaConstants) {
  61780. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61781. }
  61782. // Bind the output texture of the preivous post process as the input to this post process.
  61783. var source;
  61784. if (this._shareOutputWithPostProcess) {
  61785. source = this._shareOutputWithPostProcess.inputTexture;
  61786. }
  61787. else if (this._forcedOutputTexture) {
  61788. source = this._forcedOutputTexture;
  61789. }
  61790. else {
  61791. source = this.inputTexture;
  61792. }
  61793. this._effect._bindTexture("textureSampler", source);
  61794. // Parameters
  61795. this._effect.setVector2("scale", this._scaleRatio);
  61796. this.onApplyObservable.notifyObservers(this._effect);
  61797. return this._effect;
  61798. };
  61799. PostProcess.prototype._disposeTextures = function () {
  61800. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61801. return;
  61802. }
  61803. if (this._textures.length > 0) {
  61804. for (var i = 0; i < this._textures.length; i++) {
  61805. this._engine._releaseTexture(this._textures.data[i]);
  61806. }
  61807. }
  61808. this._textures.dispose();
  61809. };
  61810. /**
  61811. * Disposes the post process.
  61812. * @param camera The camera to dispose the post process on.
  61813. */
  61814. PostProcess.prototype.dispose = function (camera) {
  61815. camera = camera || this._camera;
  61816. this._disposeTextures();
  61817. if (this._scene) {
  61818. var index_1 = this._scene.postProcesses.indexOf(this);
  61819. if (index_1 !== -1) {
  61820. this._scene.postProcesses.splice(index_1, 1);
  61821. }
  61822. }
  61823. else {
  61824. var index_2 = this._engine.postProcesses.indexOf(this);
  61825. if (index_2 !== -1) {
  61826. this._engine.postProcesses.splice(index_2, 1);
  61827. }
  61828. }
  61829. if (!camera) {
  61830. return;
  61831. }
  61832. camera.detachPostProcess(this);
  61833. var index = camera._postProcesses.indexOf(this);
  61834. if (index === 0 && camera._postProcesses.length > 0) {
  61835. var firstPostProcess = this._camera._getFirstPostProcess();
  61836. if (firstPostProcess) {
  61837. firstPostProcess.markTextureDirty();
  61838. }
  61839. }
  61840. this.onActivateObservable.clear();
  61841. this.onAfterRenderObservable.clear();
  61842. this.onApplyObservable.clear();
  61843. this.onBeforeRenderObservable.clear();
  61844. this.onSizeChangedObservable.clear();
  61845. };
  61846. return PostProcess;
  61847. }());
  61848. BABYLON.PostProcess = PostProcess;
  61849. })(BABYLON || (BABYLON = {}));
  61850. //# sourceMappingURL=babylon.postProcess.js.map
  61851. "use strict";
  61852. var BABYLON;
  61853. (function (BABYLON) {
  61854. var PassPostProcess = /** @class */ (function (_super) {
  61855. __extends(PassPostProcess, _super);
  61856. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61857. if (camera === void 0) { camera = null; }
  61858. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61859. if (blockCompilation === void 0) { blockCompilation = false; }
  61860. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61861. }
  61862. return PassPostProcess;
  61863. }(BABYLON.PostProcess));
  61864. BABYLON.PassPostProcess = PassPostProcess;
  61865. })(BABYLON || (BABYLON = {}));
  61866. //# sourceMappingURL=babylon.passPostProcess.js.map
  61867. "use strict";
  61868. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61869. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61870. s = arguments[i];
  61871. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61872. t[p] = s[p];
  61873. }
  61874. return t;
  61875. };
  61876. var BABYLON;
  61877. (function (BABYLON) {
  61878. /**
  61879. * Default implementation IShadowGenerator.
  61880. * This is the main object responsible of generating shadows in the framework.
  61881. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61882. */
  61883. var ShadowGenerator = /** @class */ (function () {
  61884. /**
  61885. * Creates a ShadowGenerator object.
  61886. * A ShadowGenerator is the required tool to use the shadows.
  61887. * Each light casting shadows needs to use its own ShadowGenerator.
  61888. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61889. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61890. * @param light The light object generating the shadows.
  61891. * @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.
  61892. */
  61893. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61894. this._bias = 0.00005;
  61895. this._normalBias = 0;
  61896. this._blurBoxOffset = 1;
  61897. this._blurScale = 2;
  61898. this._blurKernel = 1;
  61899. this._useKernelBlur = false;
  61900. this._filter = ShadowGenerator.FILTER_NONE;
  61901. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61902. this._contactHardeningLightSizeUVRatio = 0.1;
  61903. this._darkness = 0;
  61904. this._transparencyShadow = false;
  61905. /**
  61906. * Controls the extent to which the shadows fade out at the edge of the frustum
  61907. * Used only by directionals and spots
  61908. */
  61909. this.frustumEdgeFalloff = 0;
  61910. /**
  61911. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61912. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61913. * It might on the other hand introduce peter panning.
  61914. */
  61915. this.forceBackFacesOnly = false;
  61916. this._lightDirection = BABYLON.Vector3.Zero();
  61917. this._viewMatrix = BABYLON.Matrix.Zero();
  61918. this._projectionMatrix = BABYLON.Matrix.Zero();
  61919. this._transformMatrix = BABYLON.Matrix.Zero();
  61920. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61921. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61922. this._currentFaceIndex = 0;
  61923. this._currentFaceIndexCache = 0;
  61924. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61925. this._mapSize = mapSize;
  61926. this._light = light;
  61927. this._scene = light.getScene();
  61928. light._shadowGenerator = this;
  61929. // Texture type fallback from float to int if not supported.
  61930. var caps = this._scene.getEngine().getCaps();
  61931. if (!useFullFloatFirst) {
  61932. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61933. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61934. }
  61935. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61936. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61937. }
  61938. else {
  61939. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61940. }
  61941. }
  61942. else {
  61943. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61944. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61945. }
  61946. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61947. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61948. }
  61949. else {
  61950. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61951. }
  61952. }
  61953. this._initializeGenerator();
  61954. this._applyFilterValues();
  61955. }
  61956. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61957. /**
  61958. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61959. */
  61960. get: function () {
  61961. return this._bias;
  61962. },
  61963. /**
  61964. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61965. */
  61966. set: function (bias) {
  61967. this._bias = bias;
  61968. },
  61969. enumerable: true,
  61970. configurable: true
  61971. });
  61972. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61973. /**
  61974. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61975. */
  61976. get: function () {
  61977. return this._normalBias;
  61978. },
  61979. /**
  61980. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61981. */
  61982. set: function (normalBias) {
  61983. this._normalBias = normalBias;
  61984. },
  61985. enumerable: true,
  61986. configurable: true
  61987. });
  61988. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61989. /**
  61990. * Gets the blur box offset: offset applied during the blur pass.
  61991. * Only usefull if useKernelBlur = false
  61992. */
  61993. get: function () {
  61994. return this._blurBoxOffset;
  61995. },
  61996. /**
  61997. * Sets the blur box offset: offset applied during the blur pass.
  61998. * Only usefull if useKernelBlur = false
  61999. */
  62000. set: function (value) {
  62001. if (this._blurBoxOffset === value) {
  62002. return;
  62003. }
  62004. this._blurBoxOffset = value;
  62005. this._disposeBlurPostProcesses();
  62006. },
  62007. enumerable: true,
  62008. configurable: true
  62009. });
  62010. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  62011. /**
  62012. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  62013. * 2 means half of the size.
  62014. */
  62015. get: function () {
  62016. return this._blurScale;
  62017. },
  62018. /**
  62019. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  62020. * 2 means half of the size.
  62021. */
  62022. set: function (value) {
  62023. if (this._blurScale === value) {
  62024. return;
  62025. }
  62026. this._blurScale = value;
  62027. this._disposeBlurPostProcesses();
  62028. },
  62029. enumerable: true,
  62030. configurable: true
  62031. });
  62032. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  62033. /**
  62034. * Gets the blur kernel: kernel size of the blur pass.
  62035. * Only usefull if useKernelBlur = true
  62036. */
  62037. get: function () {
  62038. return this._blurKernel;
  62039. },
  62040. /**
  62041. * Sets the blur kernel: kernel size of the blur pass.
  62042. * Only usefull if useKernelBlur = true
  62043. */
  62044. set: function (value) {
  62045. if (this._blurKernel === value) {
  62046. return;
  62047. }
  62048. this._blurKernel = value;
  62049. this._disposeBlurPostProcesses();
  62050. },
  62051. enumerable: true,
  62052. configurable: true
  62053. });
  62054. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  62055. /**
  62056. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  62057. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  62058. */
  62059. get: function () {
  62060. return this._useKernelBlur;
  62061. },
  62062. /**
  62063. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  62064. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  62065. */
  62066. set: function (value) {
  62067. if (this._useKernelBlur === value) {
  62068. return;
  62069. }
  62070. this._useKernelBlur = value;
  62071. this._disposeBlurPostProcesses();
  62072. },
  62073. enumerable: true,
  62074. configurable: true
  62075. });
  62076. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  62077. /**
  62078. * Gets the depth scale used in ESM mode.
  62079. */
  62080. get: function () {
  62081. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  62082. },
  62083. /**
  62084. * Sets the depth scale used in ESM mode.
  62085. * This can override the scale stored on the light.
  62086. */
  62087. set: function (value) {
  62088. this._depthScale = value;
  62089. },
  62090. enumerable: true,
  62091. configurable: true
  62092. });
  62093. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  62094. /**
  62095. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  62096. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  62097. */
  62098. get: function () {
  62099. return this._filter;
  62100. },
  62101. /**
  62102. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  62103. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  62104. */
  62105. set: function (value) {
  62106. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  62107. if (this._light.needCube()) {
  62108. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  62109. this.useExponentialShadowMap = true;
  62110. return;
  62111. }
  62112. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  62113. this.useCloseExponentialShadowMap = true;
  62114. return;
  62115. }
  62116. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  62117. this.usePoissonSampling = true;
  62118. return;
  62119. }
  62120. }
  62121. // Weblg1 fallback for PCF.
  62122. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  62123. if (this._scene.getEngine().webGLVersion === 1) {
  62124. this.usePoissonSampling = true;
  62125. return;
  62126. }
  62127. }
  62128. if (this._filter === value) {
  62129. return;
  62130. }
  62131. this._filter = value;
  62132. this._disposeBlurPostProcesses();
  62133. this._applyFilterValues();
  62134. this._light._markMeshesAsLightDirty();
  62135. },
  62136. enumerable: true,
  62137. configurable: true
  62138. });
  62139. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  62140. /**
  62141. * Gets if the current filter is set to Poisson Sampling.
  62142. */
  62143. get: function () {
  62144. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  62145. },
  62146. /**
  62147. * Sets the current filter to Poisson Sampling.
  62148. */
  62149. set: function (value) {
  62150. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  62151. return;
  62152. }
  62153. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  62154. },
  62155. enumerable: true,
  62156. configurable: true
  62157. });
  62158. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  62159. /**
  62160. * Gets if the current filter is set to VSM.
  62161. * DEPRECATED. Should use useExponentialShadowMap instead.
  62162. */
  62163. get: function () {
  62164. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  62165. return this.useExponentialShadowMap;
  62166. },
  62167. /**
  62168. * Sets the current filter is to VSM.
  62169. * DEPRECATED. Should use useExponentialShadowMap instead.
  62170. */
  62171. set: function (value) {
  62172. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  62173. this.useExponentialShadowMap = value;
  62174. },
  62175. enumerable: true,
  62176. configurable: true
  62177. });
  62178. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  62179. /**
  62180. * Gets if the current filter is set to blurred VSM.
  62181. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  62182. */
  62183. get: function () {
  62184. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  62185. return this.useBlurExponentialShadowMap;
  62186. },
  62187. /**
  62188. * Sets the current filter is to blurred VSM.
  62189. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  62190. */
  62191. set: function (value) {
  62192. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  62193. this.useBlurExponentialShadowMap = value;
  62194. },
  62195. enumerable: true,
  62196. configurable: true
  62197. });
  62198. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  62199. /**
  62200. * Gets if the current filter is set to ESM.
  62201. */
  62202. get: function () {
  62203. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  62204. },
  62205. /**
  62206. * Sets the current filter is to ESM.
  62207. */
  62208. set: function (value) {
  62209. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  62210. return;
  62211. }
  62212. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62213. },
  62214. enumerable: true,
  62215. configurable: true
  62216. });
  62217. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  62218. /**
  62219. * Gets if the current filter is set to filtered ESM.
  62220. */
  62221. get: function () {
  62222. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  62223. },
  62224. /**
  62225. * Gets if the current filter is set to filtered ESM.
  62226. */
  62227. set: function (value) {
  62228. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  62229. return;
  62230. }
  62231. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62232. },
  62233. enumerable: true,
  62234. configurable: true
  62235. });
  62236. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  62237. /**
  62238. * Gets if the current filter is set to "close ESM" (using the inverse of the
  62239. * exponential to prevent steep falloff artifacts).
  62240. */
  62241. get: function () {
  62242. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  62243. },
  62244. /**
  62245. * Sets the current filter to "close ESM" (using the inverse of the
  62246. * exponential to prevent steep falloff artifacts).
  62247. */
  62248. set: function (value) {
  62249. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  62250. return;
  62251. }
  62252. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62253. },
  62254. enumerable: true,
  62255. configurable: true
  62256. });
  62257. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  62258. /**
  62259. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  62260. * exponential to prevent steep falloff artifacts).
  62261. */
  62262. get: function () {
  62263. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  62264. },
  62265. /**
  62266. * Sets the current filter to filtered "close ESM" (using the inverse of the
  62267. * exponential to prevent steep falloff artifacts).
  62268. */
  62269. set: function (value) {
  62270. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  62271. return;
  62272. }
  62273. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  62274. },
  62275. enumerable: true,
  62276. configurable: true
  62277. });
  62278. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  62279. /**
  62280. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  62281. */
  62282. get: function () {
  62283. return this.filter === ShadowGenerator.FILTER_PCF;
  62284. },
  62285. /**
  62286. * Sets the current filter to "PCF" (percentage closer filtering).
  62287. */
  62288. set: function (value) {
  62289. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  62290. return;
  62291. }
  62292. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  62293. },
  62294. enumerable: true,
  62295. configurable: true
  62296. });
  62297. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  62298. /**
  62299. * Gets the PCF or PCSS Quality.
  62300. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  62301. */
  62302. get: function () {
  62303. return this._filteringQuality;
  62304. },
  62305. /**
  62306. * Sets the PCF or PCSS Quality.
  62307. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  62308. */
  62309. set: function (filteringQuality) {
  62310. this._filteringQuality = filteringQuality;
  62311. },
  62312. enumerable: true,
  62313. configurable: true
  62314. });
  62315. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  62316. /**
  62317. * Gets if the current filter is set to "PCSS" (contact hardening).
  62318. */
  62319. get: function () {
  62320. return this.filter === ShadowGenerator.FILTER_PCSS;
  62321. },
  62322. /**
  62323. * Sets the current filter to "PCSS" (contact hardening).
  62324. */
  62325. set: function (value) {
  62326. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  62327. return;
  62328. }
  62329. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  62330. },
  62331. enumerable: true,
  62332. configurable: true
  62333. });
  62334. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  62335. /**
  62336. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  62337. * Using a ratio helps keeping shape stability independently of the map size.
  62338. *
  62339. * It does not account for the light projection as it was having too much
  62340. * instability during the light setup or during light position changes.
  62341. *
  62342. * Only valid if useContactHardeningShadow is true.
  62343. */
  62344. get: function () {
  62345. return this._contactHardeningLightSizeUVRatio;
  62346. },
  62347. /**
  62348. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  62349. * Using a ratio helps keeping shape stability independently of the map size.
  62350. *
  62351. * It does not account for the light projection as it was having too much
  62352. * instability during the light setup or during light position changes.
  62353. *
  62354. * Only valid if useContactHardeningShadow is true.
  62355. */
  62356. set: function (contactHardeningLightSizeUVRatio) {
  62357. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  62358. },
  62359. enumerable: true,
  62360. configurable: true
  62361. });
  62362. /**
  62363. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  62364. * 0 means strongest and 1 would means no shadow.
  62365. * @returns the darkness.
  62366. */
  62367. ShadowGenerator.prototype.getDarkness = function () {
  62368. return this._darkness;
  62369. };
  62370. /**
  62371. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  62372. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  62373. * @returns the shadow generator allowing fluent coding.
  62374. */
  62375. ShadowGenerator.prototype.setDarkness = function (darkness) {
  62376. if (darkness >= 1.0)
  62377. this._darkness = 1.0;
  62378. else if (darkness <= 0.0)
  62379. this._darkness = 0.0;
  62380. else
  62381. this._darkness = darkness;
  62382. return this;
  62383. };
  62384. /**
  62385. * Sets the ability to have transparent shadow (boolean).
  62386. * @param transparent True if transparent else False
  62387. * @returns the shadow generator allowing fluent coding
  62388. */
  62389. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  62390. this._transparencyShadow = transparent;
  62391. return this;
  62392. };
  62393. /**
  62394. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  62395. * @returns The render target texture if present otherwise, null
  62396. */
  62397. ShadowGenerator.prototype.getShadowMap = function () {
  62398. return this._shadowMap;
  62399. };
  62400. /**
  62401. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  62402. * @returns The render target texture if the shadow map is present otherwise, null
  62403. */
  62404. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  62405. if (this._shadowMap2) {
  62406. return this._shadowMap2;
  62407. }
  62408. return this._shadowMap;
  62409. };
  62410. /**
  62411. * Helper function to add a mesh and its descendants to the list of shadow casters.
  62412. * @param mesh Mesh to add
  62413. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  62414. * @returns the Shadow Generator itself
  62415. */
  62416. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  62417. if (includeDescendants === void 0) { includeDescendants = true; }
  62418. if (!this._shadowMap) {
  62419. return this;
  62420. }
  62421. if (!this._shadowMap.renderList) {
  62422. this._shadowMap.renderList = [];
  62423. }
  62424. this._shadowMap.renderList.push(mesh);
  62425. if (includeDescendants) {
  62426. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  62427. }
  62428. return this;
  62429. var _a;
  62430. };
  62431. /**
  62432. * Helper function to remove a mesh and its descendants from the list of shadow casters
  62433. * @param mesh Mesh to remove
  62434. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  62435. * @returns the Shadow Generator itself
  62436. */
  62437. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  62438. if (includeDescendants === void 0) { includeDescendants = true; }
  62439. if (!this._shadowMap || !this._shadowMap.renderList) {
  62440. return this;
  62441. }
  62442. var index = this._shadowMap.renderList.indexOf(mesh);
  62443. if (index !== -1) {
  62444. this._shadowMap.renderList.splice(index, 1);
  62445. }
  62446. if (includeDescendants) {
  62447. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  62448. var child = _a[_i];
  62449. this.removeShadowCaster(child);
  62450. }
  62451. }
  62452. return this;
  62453. };
  62454. /**
  62455. * Returns the associated light object.
  62456. * @returns the light generating the shadow
  62457. */
  62458. ShadowGenerator.prototype.getLight = function () {
  62459. return this._light;
  62460. };
  62461. ShadowGenerator.prototype._initializeGenerator = function () {
  62462. this._light._markMeshesAsLightDirty();
  62463. this._initializeShadowMap();
  62464. };
  62465. ShadowGenerator.prototype._initializeShadowMap = function () {
  62466. var _this = this;
  62467. // Render target
  62468. var engine = this._scene.getEngine();
  62469. if (engine.webGLVersion > 1) {
  62470. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  62471. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  62472. }
  62473. else {
  62474. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  62475. }
  62476. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62477. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62478. this._shadowMap.anisotropicFilteringLevel = 1;
  62479. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62480. this._shadowMap.renderParticles = false;
  62481. this._shadowMap.ignoreCameraViewport = true;
  62482. // Record Face Index before render.
  62483. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  62484. _this._currentFaceIndex = faceIndex;
  62485. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  62486. engine.setColorWrite(false);
  62487. }
  62488. });
  62489. // Custom render function.
  62490. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  62491. // Blur if required afer render.
  62492. this._shadowMap.onAfterUnbindObservable.add(function () {
  62493. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  62494. engine.setColorWrite(true);
  62495. }
  62496. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  62497. return;
  62498. }
  62499. var shadowMap = _this.getShadowMapForRendering();
  62500. if (shadowMap) {
  62501. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  62502. }
  62503. });
  62504. // Clear according to the chosen filter.
  62505. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  62506. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  62507. this._shadowMap.onClearObservable.add(function (engine) {
  62508. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  62509. engine.clear(clearOne, false, true, false);
  62510. }
  62511. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  62512. engine.clear(clearZero, true, true, false);
  62513. }
  62514. else {
  62515. engine.clear(clearOne, true, true, false);
  62516. }
  62517. });
  62518. };
  62519. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  62520. var _this = this;
  62521. var engine = this._scene.getEngine();
  62522. var targetSize = this._mapSize / this.blurScale;
  62523. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  62524. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  62525. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62526. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62527. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62528. }
  62529. if (this.useKernelBlur) {
  62530. 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);
  62531. this._kernelBlurXPostprocess.width = targetSize;
  62532. this._kernelBlurXPostprocess.height = targetSize;
  62533. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  62534. effect.setTexture("textureSampler", _this._shadowMap);
  62535. });
  62536. 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);
  62537. this._kernelBlurXPostprocess.autoClear = false;
  62538. this._kernelBlurYPostprocess.autoClear = false;
  62539. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62540. this._kernelBlurXPostprocess.packedFloat = true;
  62541. this._kernelBlurYPostprocess.packedFloat = true;
  62542. }
  62543. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  62544. }
  62545. else {
  62546. 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);
  62547. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  62548. effect.setFloat2("screenSize", targetSize, targetSize);
  62549. effect.setTexture("textureSampler", _this._shadowMap);
  62550. });
  62551. this._boxBlurPostprocess.autoClear = false;
  62552. this._blurPostProcesses = [this._boxBlurPostprocess];
  62553. }
  62554. };
  62555. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62556. var index;
  62557. var engine = this._scene.getEngine();
  62558. if (depthOnlySubMeshes.length) {
  62559. engine.setColorWrite(false);
  62560. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62561. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  62562. }
  62563. engine.setColorWrite(true);
  62564. }
  62565. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62566. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  62567. }
  62568. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62569. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  62570. }
  62571. if (this._transparencyShadow) {
  62572. for (index = 0; index < transparentSubMeshes.length; index++) {
  62573. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  62574. }
  62575. }
  62576. };
  62577. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  62578. var _this = this;
  62579. var mesh = subMesh.getRenderingMesh();
  62580. var scene = this._scene;
  62581. var engine = scene.getEngine();
  62582. var material = subMesh.getMaterial();
  62583. if (!material) {
  62584. return;
  62585. }
  62586. // Culling
  62587. engine.setState(material.backFaceCulling);
  62588. // Managing instances
  62589. var batch = mesh._getInstancesRenderList(subMesh._id);
  62590. if (batch.mustReturn) {
  62591. return;
  62592. }
  62593. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  62594. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  62595. engine.enableEffect(this._effect);
  62596. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  62597. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  62598. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  62599. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62600. this._effect.setVector3("lightData", this._cachedDirection);
  62601. }
  62602. else {
  62603. this._effect.setVector3("lightData", this._cachedPosition);
  62604. }
  62605. if (scene.activeCamera) {
  62606. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  62607. }
  62608. // Alpha test
  62609. if (material && material.needAlphaTesting()) {
  62610. var alphaTexture = material.getAlphaTestTexture();
  62611. if (alphaTexture) {
  62612. this._effect.setTexture("diffuseSampler", alphaTexture);
  62613. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  62614. }
  62615. }
  62616. // Bones
  62617. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62618. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  62619. }
  62620. // Morph targets
  62621. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  62622. if (this.forceBackFacesOnly) {
  62623. engine.setState(true, 0, false, true);
  62624. }
  62625. // Draw
  62626. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  62627. if (this.forceBackFacesOnly) {
  62628. engine.setState(true, 0, false, false);
  62629. }
  62630. }
  62631. else {
  62632. // Need to reset refresh rate of the shadowMap
  62633. if (this._shadowMap) {
  62634. this._shadowMap.resetRefreshCounter();
  62635. }
  62636. }
  62637. };
  62638. ShadowGenerator.prototype._applyFilterValues = function () {
  62639. if (!this._shadowMap) {
  62640. return;
  62641. }
  62642. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  62643. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  62644. }
  62645. else {
  62646. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62647. }
  62648. };
  62649. /**
  62650. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62651. * @param onCompiled Callback triggered at the and of the effects compilation
  62652. * @param options Sets of optional options forcing the compilation with different modes
  62653. */
  62654. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  62655. var _this = this;
  62656. var localOptions = __assign({ useInstances: false }, options);
  62657. var shadowMap = this.getShadowMap();
  62658. if (!shadowMap) {
  62659. if (onCompiled) {
  62660. onCompiled(this);
  62661. }
  62662. return;
  62663. }
  62664. var renderList = shadowMap.renderList;
  62665. if (!renderList) {
  62666. if (onCompiled) {
  62667. onCompiled(this);
  62668. }
  62669. return;
  62670. }
  62671. var subMeshes = new Array();
  62672. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  62673. var mesh = renderList_1[_i];
  62674. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  62675. }
  62676. if (subMeshes.length === 0) {
  62677. if (onCompiled) {
  62678. onCompiled(this);
  62679. }
  62680. return;
  62681. }
  62682. var currentIndex = 0;
  62683. var checkReady = function () {
  62684. if (!_this._scene || !_this._scene.getEngine()) {
  62685. return;
  62686. }
  62687. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  62688. currentIndex++;
  62689. if (currentIndex >= subMeshes.length) {
  62690. if (onCompiled) {
  62691. onCompiled(_this);
  62692. }
  62693. return;
  62694. }
  62695. }
  62696. setTimeout(checkReady, 16);
  62697. };
  62698. checkReady();
  62699. };
  62700. /**
  62701. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  62702. * @param options Sets of optional options forcing the compilation with different modes
  62703. * @returns A promise that resolves when the compilation completes
  62704. */
  62705. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  62706. var _this = this;
  62707. return new Promise(function (resolve) {
  62708. _this.forceCompilation(function () {
  62709. resolve();
  62710. }, options);
  62711. });
  62712. };
  62713. /**
  62714. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  62715. * @param subMesh The submesh we want to render in the shadow map
  62716. * @param useInstances Defines wether will draw in the map using instances
  62717. * @returns true if ready otherwise, false
  62718. */
  62719. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  62720. var defines = [];
  62721. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62722. defines.push("#define FLOAT");
  62723. }
  62724. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62725. defines.push("#define ESM");
  62726. }
  62727. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  62728. defines.push("#define DEPTHTEXTURE");
  62729. }
  62730. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62731. var mesh = subMesh.getMesh();
  62732. var material = subMesh.getMaterial();
  62733. // Normal bias.
  62734. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  62735. attribs.push(BABYLON.VertexBuffer.NormalKind);
  62736. defines.push("#define NORMAL");
  62737. if (mesh.nonUniformScaling) {
  62738. defines.push("#define NONUNIFORMSCALING");
  62739. }
  62740. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  62741. defines.push("#define DIRECTIONINLIGHTDATA");
  62742. }
  62743. }
  62744. // Alpha test
  62745. if (material && material.needAlphaTesting()) {
  62746. var alphaTexture = material.getAlphaTestTexture();
  62747. if (alphaTexture) {
  62748. defines.push("#define ALPHATEST");
  62749. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62750. attribs.push(BABYLON.VertexBuffer.UVKind);
  62751. defines.push("#define UV1");
  62752. }
  62753. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62754. if (alphaTexture.coordinatesIndex === 1) {
  62755. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62756. defines.push("#define UV2");
  62757. }
  62758. }
  62759. }
  62760. }
  62761. // Bones
  62762. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62763. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62764. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62765. if (mesh.numBoneInfluencers > 4) {
  62766. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62767. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62768. }
  62769. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62770. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62771. }
  62772. else {
  62773. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62774. }
  62775. // Morph targets
  62776. var manager = mesh.morphTargetManager;
  62777. var morphInfluencers = 0;
  62778. if (manager) {
  62779. if (manager.numInfluencers > 0) {
  62780. defines.push("#define MORPHTARGETS");
  62781. morphInfluencers = manager.numInfluencers;
  62782. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62783. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62784. }
  62785. }
  62786. // Instances
  62787. if (useInstances) {
  62788. defines.push("#define INSTANCES");
  62789. attribs.push("world0");
  62790. attribs.push("world1");
  62791. attribs.push("world2");
  62792. attribs.push("world3");
  62793. }
  62794. // Get correct effect
  62795. var join = defines.join("\n");
  62796. if (this._cachedDefines !== join) {
  62797. this._cachedDefines = join;
  62798. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62799. }
  62800. if (!this._effect.isReady()) {
  62801. return false;
  62802. }
  62803. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62804. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62805. this._initializeBlurRTTAndPostProcesses();
  62806. }
  62807. }
  62808. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62809. return false;
  62810. }
  62811. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62812. return false;
  62813. }
  62814. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62815. return false;
  62816. }
  62817. return true;
  62818. };
  62819. /**
  62820. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62821. * @param defines Defines of the material we want to update
  62822. * @param lightIndex Index of the light in the enabled light list of the material
  62823. */
  62824. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62825. var scene = this._scene;
  62826. var light = this._light;
  62827. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62828. return;
  62829. }
  62830. defines["SHADOW" + lightIndex] = true;
  62831. if (this.useContactHardeningShadow) {
  62832. defines["SHADOWPCSS" + lightIndex] = true;
  62833. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62834. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62835. }
  62836. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62837. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62838. }
  62839. // else default to high.
  62840. }
  62841. if (this.usePercentageCloserFiltering) {
  62842. defines["SHADOWPCF" + lightIndex] = true;
  62843. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62844. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62845. }
  62846. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62847. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62848. }
  62849. // else default to high.
  62850. }
  62851. else if (this.usePoissonSampling) {
  62852. defines["SHADOWPOISSON" + lightIndex] = true;
  62853. }
  62854. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62855. defines["SHADOWESM" + lightIndex] = true;
  62856. }
  62857. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62858. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62859. }
  62860. if (light.needCube()) {
  62861. defines["SHADOWCUBE" + lightIndex] = true;
  62862. }
  62863. };
  62864. /**
  62865. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62866. * defined in the generator but impacting the effect).
  62867. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62868. * @param effect The effect we are binfing the information for
  62869. */
  62870. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62871. var light = this._light;
  62872. var scene = this._scene;
  62873. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62874. return;
  62875. }
  62876. var camera = scene.activeCamera;
  62877. if (!camera) {
  62878. return;
  62879. }
  62880. var shadowMap = this.getShadowMap();
  62881. if (!shadowMap) {
  62882. return;
  62883. }
  62884. if (!light.needCube()) {
  62885. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62886. }
  62887. // Only PCF uses depth stencil texture.
  62888. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62889. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62890. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62891. }
  62892. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62893. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62894. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62895. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62896. }
  62897. else {
  62898. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62899. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62900. }
  62901. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62902. };
  62903. /**
  62904. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62905. * (eq to shadow prjection matrix * light transform matrix)
  62906. * @returns The transform matrix used to create the shadow map
  62907. */
  62908. ShadowGenerator.prototype.getTransformMatrix = function () {
  62909. var scene = this._scene;
  62910. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62911. return this._transformMatrix;
  62912. }
  62913. this._currentRenderID = scene.getRenderId();
  62914. this._currentFaceIndexCache = this._currentFaceIndex;
  62915. var lightPosition = this._light.position;
  62916. if (this._light.computeTransformedInformation()) {
  62917. lightPosition = this._light.transformedPosition;
  62918. }
  62919. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62920. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62921. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62922. }
  62923. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62924. this._cachedPosition.copyFrom(lightPosition);
  62925. this._cachedDirection.copyFrom(this._lightDirection);
  62926. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62927. var shadowMap = this.getShadowMap();
  62928. if (shadowMap) {
  62929. var renderList = shadowMap.renderList;
  62930. if (renderList) {
  62931. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62932. }
  62933. }
  62934. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62935. }
  62936. return this._transformMatrix;
  62937. };
  62938. /**
  62939. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62940. * Cube and 2D textures for instance.
  62941. */
  62942. ShadowGenerator.prototype.recreateShadowMap = function () {
  62943. var shadowMap = this._shadowMap;
  62944. if (!shadowMap) {
  62945. return;
  62946. }
  62947. // Track render list.
  62948. var renderList = shadowMap.renderList;
  62949. // Clean up existing data.
  62950. this._disposeRTTandPostProcesses();
  62951. // Reinitializes.
  62952. this._initializeGenerator();
  62953. // Reaffect the filter to ensure a correct fallback if necessary.
  62954. this.filter = this.filter;
  62955. // Reaffect the filter.
  62956. this._applyFilterValues();
  62957. // Reaffect Render List.
  62958. this._shadowMap.renderList = renderList;
  62959. };
  62960. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62961. if (this._shadowMap2) {
  62962. this._shadowMap2.dispose();
  62963. this._shadowMap2 = null;
  62964. }
  62965. if (this._boxBlurPostprocess) {
  62966. this._boxBlurPostprocess.dispose();
  62967. this._boxBlurPostprocess = null;
  62968. }
  62969. if (this._kernelBlurXPostprocess) {
  62970. this._kernelBlurXPostprocess.dispose();
  62971. this._kernelBlurXPostprocess = null;
  62972. }
  62973. if (this._kernelBlurYPostprocess) {
  62974. this._kernelBlurYPostprocess.dispose();
  62975. this._kernelBlurYPostprocess = null;
  62976. }
  62977. this._blurPostProcesses = [];
  62978. };
  62979. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62980. if (this._shadowMap) {
  62981. this._shadowMap.dispose();
  62982. this._shadowMap = null;
  62983. }
  62984. this._disposeBlurPostProcesses();
  62985. };
  62986. /**
  62987. * Disposes the ShadowGenerator.
  62988. * Returns nothing.
  62989. */
  62990. ShadowGenerator.prototype.dispose = function () {
  62991. this._disposeRTTandPostProcesses();
  62992. if (this._light) {
  62993. this._light._shadowGenerator = null;
  62994. this._light._markMeshesAsLightDirty();
  62995. }
  62996. };
  62997. /**
  62998. * Serializes the shadow generator setup to a json object.
  62999. * @returns The serialized JSON object
  63000. */
  63001. ShadowGenerator.prototype.serialize = function () {
  63002. var serializationObject = {};
  63003. var shadowMap = this.getShadowMap();
  63004. if (!shadowMap) {
  63005. return serializationObject;
  63006. }
  63007. serializationObject.lightId = this._light.id;
  63008. serializationObject.mapSize = shadowMap.getRenderSize();
  63009. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  63010. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  63011. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  63012. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  63013. serializationObject.usePoissonSampling = this.usePoissonSampling;
  63014. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  63015. serializationObject.depthScale = this.depthScale;
  63016. serializationObject.darkness = this.getDarkness();
  63017. serializationObject.blurBoxOffset = this.blurBoxOffset;
  63018. serializationObject.blurKernel = this.blurKernel;
  63019. serializationObject.blurScale = this.blurScale;
  63020. serializationObject.useKernelBlur = this.useKernelBlur;
  63021. serializationObject.transparencyShadow = this._transparencyShadow;
  63022. serializationObject.bias = this.bias;
  63023. serializationObject.normalBias = this.normalBias;
  63024. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  63025. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  63026. serializationObject.filteringQuality = this.filteringQuality;
  63027. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  63028. serializationObject.renderList = [];
  63029. if (shadowMap.renderList) {
  63030. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  63031. var mesh = shadowMap.renderList[meshIndex];
  63032. serializationObject.renderList.push(mesh.id);
  63033. }
  63034. }
  63035. return serializationObject;
  63036. };
  63037. /**
  63038. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  63039. * @param parsedShadowGenerator The JSON object to parse
  63040. * @param scene The scene to create the shadow map for
  63041. * @returns The parsed shadow generator
  63042. */
  63043. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  63044. //casting to point light, as light is missing the position attr and typescript complains.
  63045. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  63046. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  63047. var shadowMap = shadowGenerator.getShadowMap();
  63048. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  63049. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  63050. meshes.forEach(function (mesh) {
  63051. if (!shadowMap) {
  63052. return;
  63053. }
  63054. if (!shadowMap.renderList) {
  63055. shadowMap.renderList = [];
  63056. }
  63057. shadowMap.renderList.push(mesh);
  63058. });
  63059. }
  63060. if (parsedShadowGenerator.usePoissonSampling) {
  63061. shadowGenerator.usePoissonSampling = true;
  63062. }
  63063. else if (parsedShadowGenerator.useExponentialShadowMap) {
  63064. shadowGenerator.useExponentialShadowMap = true;
  63065. }
  63066. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  63067. shadowGenerator.useBlurExponentialShadowMap = true;
  63068. }
  63069. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  63070. shadowGenerator.useCloseExponentialShadowMap = true;
  63071. }
  63072. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  63073. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  63074. }
  63075. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  63076. shadowGenerator.usePercentageCloserFiltering = true;
  63077. }
  63078. else if (parsedShadowGenerator.useContactHardeningShadow) {
  63079. shadowGenerator.useContactHardeningShadow = true;
  63080. }
  63081. if (parsedShadowGenerator.filteringQuality) {
  63082. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  63083. }
  63084. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  63085. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  63086. }
  63087. else if (parsedShadowGenerator.useVarianceShadowMap) {
  63088. shadowGenerator.useExponentialShadowMap = true;
  63089. }
  63090. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  63091. shadowGenerator.useBlurExponentialShadowMap = true;
  63092. }
  63093. if (parsedShadowGenerator.depthScale) {
  63094. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  63095. }
  63096. if (parsedShadowGenerator.blurScale) {
  63097. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  63098. }
  63099. if (parsedShadowGenerator.blurBoxOffset) {
  63100. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  63101. }
  63102. if (parsedShadowGenerator.useKernelBlur) {
  63103. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  63104. }
  63105. if (parsedShadowGenerator.blurKernel) {
  63106. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  63107. }
  63108. if (parsedShadowGenerator.bias !== undefined) {
  63109. shadowGenerator.bias = parsedShadowGenerator.bias;
  63110. }
  63111. if (parsedShadowGenerator.normalBias !== undefined) {
  63112. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  63113. }
  63114. if (parsedShadowGenerator.darkness) {
  63115. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  63116. }
  63117. if (parsedShadowGenerator.transparencyShadow) {
  63118. shadowGenerator.setTransparencyShadow(true);
  63119. }
  63120. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  63121. return shadowGenerator;
  63122. };
  63123. /**
  63124. * Shadow generator mode None: no filtering applied.
  63125. */
  63126. ShadowGenerator.FILTER_NONE = 0;
  63127. /**
  63128. * Shadow generator mode ESM: Exponential Shadow Mapping.
  63129. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63130. */
  63131. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  63132. /**
  63133. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  63134. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  63135. */
  63136. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  63137. /**
  63138. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  63139. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63140. */
  63141. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  63142. /**
  63143. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  63144. * edge artifacts on steep falloff.
  63145. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63146. */
  63147. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  63148. /**
  63149. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  63150. * edge artifacts on steep falloff.
  63151. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  63152. */
  63153. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  63154. /**
  63155. * Shadow generator mode PCF: Percentage Closer Filtering
  63156. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  63157. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  63158. */
  63159. ShadowGenerator.FILTER_PCF = 6;
  63160. /**
  63161. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  63162. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  63163. * Contact Hardening
  63164. */
  63165. ShadowGenerator.FILTER_PCSS = 7;
  63166. /**
  63167. * Reserved for PCF and PCSS
  63168. * Highest Quality.
  63169. *
  63170. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  63171. *
  63172. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  63173. */
  63174. ShadowGenerator.QUALITY_HIGH = 0;
  63175. /**
  63176. * Reserved for PCF and PCSS
  63177. * Good tradeoff for quality/perf cross devices
  63178. *
  63179. * Execute PCF on a 3*3 kernel.
  63180. *
  63181. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  63182. */
  63183. ShadowGenerator.QUALITY_MEDIUM = 1;
  63184. /**
  63185. * Reserved for PCF and PCSS
  63186. * The lowest quality but the fastest.
  63187. *
  63188. * Execute PCF on a 1*1 kernel.
  63189. *
  63190. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  63191. */
  63192. ShadowGenerator.QUALITY_LOW = 2;
  63193. return ShadowGenerator;
  63194. }());
  63195. BABYLON.ShadowGenerator = ShadowGenerator;
  63196. })(BABYLON || (BABYLON = {}));
  63197. //# sourceMappingURL=babylon.shadowGenerator.js.map
  63198. "use strict";
  63199. var BABYLON;
  63200. (function (BABYLON) {
  63201. var DefaultLoadingScreen = /** @class */ (function () {
  63202. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  63203. if (_loadingText === void 0) { _loadingText = ""; }
  63204. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  63205. var _this = this;
  63206. this._renderingCanvas = _renderingCanvas;
  63207. this._loadingText = _loadingText;
  63208. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  63209. // Resize
  63210. this._resizeLoadingUI = function () {
  63211. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  63212. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  63213. if (!_this._loadingDiv) {
  63214. return;
  63215. }
  63216. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  63217. _this._loadingDiv.style.left = canvasRect.left + "px";
  63218. _this._loadingDiv.style.top = canvasRect.top + "px";
  63219. _this._loadingDiv.style.width = canvasRect.width + "px";
  63220. _this._loadingDiv.style.height = canvasRect.height + "px";
  63221. };
  63222. }
  63223. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  63224. if (this._loadingDiv) {
  63225. // Do not add a loading screen if there is already one
  63226. return;
  63227. }
  63228. this._loadingDiv = document.createElement("div");
  63229. this._loadingDiv.id = "babylonjsLoadingDiv";
  63230. this._loadingDiv.style.opacity = "0";
  63231. this._loadingDiv.style.transition = "opacity 1.5s ease";
  63232. this._loadingDiv.style.pointerEvents = "none";
  63233. // Loading text
  63234. this._loadingTextDiv = document.createElement("div");
  63235. this._loadingTextDiv.style.position = "absolute";
  63236. this._loadingTextDiv.style.left = "0";
  63237. this._loadingTextDiv.style.top = "50%";
  63238. this._loadingTextDiv.style.marginTop = "80px";
  63239. this._loadingTextDiv.style.width = "100%";
  63240. this._loadingTextDiv.style.height = "20px";
  63241. this._loadingTextDiv.style.fontFamily = "Arial";
  63242. this._loadingTextDiv.style.fontSize = "14px";
  63243. this._loadingTextDiv.style.color = "white";
  63244. this._loadingTextDiv.style.textAlign = "center";
  63245. this._loadingTextDiv.innerHTML = "Loading";
  63246. this._loadingDiv.appendChild(this._loadingTextDiv);
  63247. //set the predefined text
  63248. this._loadingTextDiv.innerHTML = this._loadingText;
  63249. // Generating keyframes
  63250. var style = document.createElement('style');
  63251. style.type = 'text/css';
  63252. 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 }";
  63253. style.innerHTML = keyFrames;
  63254. document.getElementsByTagName('head')[0].appendChild(style);
  63255. // Loading img
  63256. var imgBack = new Image();
  63257. 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";
  63258. imgBack.style.position = "absolute";
  63259. imgBack.style.left = "50%";
  63260. imgBack.style.top = "50%";
  63261. imgBack.style.marginLeft = "-60px";
  63262. imgBack.style.marginTop = "-60px";
  63263. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  63264. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  63265. imgBack.style.transformOrigin = "50% 50%";
  63266. imgBack.style.webkitTransformOrigin = "50% 50%";
  63267. this._loadingDiv.appendChild(imgBack);
  63268. this._resizeLoadingUI();
  63269. window.addEventListener("resize", this._resizeLoadingUI);
  63270. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  63271. document.body.appendChild(this._loadingDiv);
  63272. this._loadingDiv.style.opacity = "1";
  63273. };
  63274. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  63275. var _this = this;
  63276. if (!this._loadingDiv) {
  63277. return;
  63278. }
  63279. var onTransitionEnd = function () {
  63280. if (!_this._loadingDiv) {
  63281. return;
  63282. }
  63283. document.body.removeChild(_this._loadingDiv);
  63284. window.removeEventListener("resize", _this._resizeLoadingUI);
  63285. _this._loadingDiv = null;
  63286. };
  63287. this._loadingDiv.style.opacity = "0";
  63288. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  63289. };
  63290. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  63291. set: function (text) {
  63292. this._loadingText = text;
  63293. if (this._loadingTextDiv) {
  63294. this._loadingTextDiv.innerHTML = this._loadingText;
  63295. }
  63296. },
  63297. enumerable: true,
  63298. configurable: true
  63299. });
  63300. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  63301. get: function () {
  63302. return this._loadingDivBackgroundColor;
  63303. },
  63304. set: function (color) {
  63305. this._loadingDivBackgroundColor = color;
  63306. if (!this._loadingDiv) {
  63307. return;
  63308. }
  63309. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  63310. },
  63311. enumerable: true,
  63312. configurable: true
  63313. });
  63314. return DefaultLoadingScreen;
  63315. }());
  63316. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  63317. })(BABYLON || (BABYLON = {}));
  63318. //# sourceMappingURL=babylon.loadingScreen.js.map
  63319. "use strict";
  63320. var BABYLON;
  63321. (function (BABYLON) {
  63322. var SceneLoaderProgressEvent = /** @class */ (function () {
  63323. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  63324. this.lengthComputable = lengthComputable;
  63325. this.loaded = loaded;
  63326. this.total = total;
  63327. }
  63328. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  63329. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  63330. };
  63331. return SceneLoaderProgressEvent;
  63332. }());
  63333. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  63334. var SceneLoader = /** @class */ (function () {
  63335. function SceneLoader() {
  63336. }
  63337. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  63338. get: function () {
  63339. return 0;
  63340. },
  63341. enumerable: true,
  63342. configurable: true
  63343. });
  63344. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  63345. get: function () {
  63346. return 1;
  63347. },
  63348. enumerable: true,
  63349. configurable: true
  63350. });
  63351. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  63352. get: function () {
  63353. return 2;
  63354. },
  63355. enumerable: true,
  63356. configurable: true
  63357. });
  63358. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  63359. get: function () {
  63360. return 3;
  63361. },
  63362. enumerable: true,
  63363. configurable: true
  63364. });
  63365. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  63366. get: function () {
  63367. return SceneLoader._ForceFullSceneLoadingForIncremental;
  63368. },
  63369. set: function (value) {
  63370. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  63371. },
  63372. enumerable: true,
  63373. configurable: true
  63374. });
  63375. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  63376. get: function () {
  63377. return SceneLoader._ShowLoadingScreen;
  63378. },
  63379. set: function (value) {
  63380. SceneLoader._ShowLoadingScreen = value;
  63381. },
  63382. enumerable: true,
  63383. configurable: true
  63384. });
  63385. Object.defineProperty(SceneLoader, "loggingLevel", {
  63386. get: function () {
  63387. return SceneLoader._loggingLevel;
  63388. },
  63389. set: function (value) {
  63390. SceneLoader._loggingLevel = value;
  63391. },
  63392. enumerable: true,
  63393. configurable: true
  63394. });
  63395. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  63396. get: function () {
  63397. return SceneLoader._CleanBoneMatrixWeights;
  63398. },
  63399. set: function (value) {
  63400. SceneLoader._CleanBoneMatrixWeights = value;
  63401. },
  63402. enumerable: true,
  63403. configurable: true
  63404. });
  63405. SceneLoader._getDefaultPlugin = function () {
  63406. return SceneLoader._registeredPlugins[".babylon"];
  63407. };
  63408. SceneLoader._getPluginForExtension = function (extension) {
  63409. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  63410. if (registeredPlugin) {
  63411. return registeredPlugin;
  63412. }
  63413. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  63414. return SceneLoader._getDefaultPlugin();
  63415. };
  63416. SceneLoader._getPluginForDirectLoad = function (data) {
  63417. for (var extension in SceneLoader._registeredPlugins) {
  63418. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  63419. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  63420. return SceneLoader._registeredPlugins[extension];
  63421. }
  63422. }
  63423. return SceneLoader._getDefaultPlugin();
  63424. };
  63425. SceneLoader._getPluginForFilename = function (sceneFilename) {
  63426. if (sceneFilename.name) {
  63427. sceneFilename = sceneFilename.name;
  63428. }
  63429. var queryStringPosition = sceneFilename.indexOf("?");
  63430. if (queryStringPosition !== -1) {
  63431. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  63432. }
  63433. var dotPosition = sceneFilename.lastIndexOf(".");
  63434. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  63435. return SceneLoader._getPluginForExtension(extension);
  63436. };
  63437. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  63438. SceneLoader._getDirectLoad = function (sceneFilename) {
  63439. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  63440. return sceneFilename.substr(5);
  63441. }
  63442. return null;
  63443. };
  63444. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  63445. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  63446. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  63447. var plugin;
  63448. if (registeredPlugin.plugin.createPlugin) {
  63449. plugin = registeredPlugin.plugin.createPlugin();
  63450. }
  63451. else {
  63452. plugin = registeredPlugin.plugin;
  63453. }
  63454. var useArrayBuffer = registeredPlugin.isBinary;
  63455. var database;
  63456. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  63457. var dataCallback = function (data, responseURL) {
  63458. if (scene.isDisposed) {
  63459. onError("Scene has been disposed");
  63460. return;
  63461. }
  63462. scene.database = database;
  63463. onSuccess(plugin, data, responseURL);
  63464. };
  63465. var request = null;
  63466. var pluginDisposed = false;
  63467. var onDisposeObservable = plugin.onDisposeObservable;
  63468. if (onDisposeObservable) {
  63469. onDisposeObservable.add(function () {
  63470. pluginDisposed = true;
  63471. if (request) {
  63472. request.abort();
  63473. request = null;
  63474. }
  63475. onDispose();
  63476. });
  63477. }
  63478. var manifestChecked = function () {
  63479. if (pluginDisposed) {
  63480. return;
  63481. }
  63482. var url = rootUrl + sceneFilename;
  63483. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  63484. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  63485. } : undefined, database, useArrayBuffer, function (request, exception) {
  63486. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  63487. });
  63488. };
  63489. if (directLoad) {
  63490. dataCallback(directLoad);
  63491. return plugin;
  63492. }
  63493. if (rootUrl.indexOf("file:") === -1) {
  63494. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  63495. if (canUseOfflineSupport) {
  63496. // Also check for exceptions
  63497. var exceptionFound = false;
  63498. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  63499. var regex = _a[_i];
  63500. if (regex.test(rootUrl + sceneFilename)) {
  63501. exceptionFound = true;
  63502. break;
  63503. }
  63504. }
  63505. canUseOfflineSupport = !exceptionFound;
  63506. }
  63507. if (canUseOfflineSupport) {
  63508. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  63509. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  63510. }
  63511. else {
  63512. manifestChecked();
  63513. }
  63514. }
  63515. else {
  63516. var fileOrString = sceneFilename;
  63517. if (fileOrString.name) {
  63518. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  63519. }
  63520. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  63521. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  63522. }
  63523. else {
  63524. onError("Unable to find file named " + sceneFilename);
  63525. }
  63526. }
  63527. return plugin;
  63528. };
  63529. // Public functions
  63530. SceneLoader.GetPluginForExtension = function (extension) {
  63531. return SceneLoader._getPluginForExtension(extension).plugin;
  63532. };
  63533. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  63534. return !!SceneLoader._registeredPlugins[extension];
  63535. };
  63536. SceneLoader.RegisterPlugin = function (plugin) {
  63537. if (typeof plugin.extensions === "string") {
  63538. var extension = plugin.extensions;
  63539. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  63540. plugin: plugin,
  63541. isBinary: false
  63542. };
  63543. }
  63544. else {
  63545. var extensions = plugin.extensions;
  63546. Object.keys(extensions).forEach(function (extension) {
  63547. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  63548. plugin: plugin,
  63549. isBinary: extensions[extension].isBinary
  63550. };
  63551. });
  63552. }
  63553. };
  63554. /**
  63555. * Import meshes into a scene
  63556. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  63557. * @param rootUrl a string that defines the root url for scene and resources
  63558. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63559. * @param scene the instance of BABYLON.Scene to append to
  63560. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  63561. * @param onProgress a callback with a progress event for each file being loaded
  63562. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63563. * @param pluginExtension the extension used to determine the plugin
  63564. * @returns The loaded plugin
  63565. */
  63566. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63567. if (onSuccess === void 0) { onSuccess = null; }
  63568. if (onProgress === void 0) { onProgress = null; }
  63569. if (onError === void 0) { onError = null; }
  63570. if (pluginExtension === void 0) { pluginExtension = null; }
  63571. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63572. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63573. return null;
  63574. }
  63575. var loadingToken = {};
  63576. scene._addPendingData(loadingToken);
  63577. var disposeHandler = function () {
  63578. scene._removePendingData(loadingToken);
  63579. };
  63580. var errorHandler = function (message, exception) {
  63581. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  63582. if (onError) {
  63583. onError(scene, errorMessage, exception);
  63584. }
  63585. else {
  63586. BABYLON.Tools.Error(errorMessage);
  63587. // should the exception be thrown?
  63588. }
  63589. disposeHandler();
  63590. };
  63591. var progressHandler = onProgress ? function (event) {
  63592. try {
  63593. onProgress(event);
  63594. }
  63595. catch (e) {
  63596. errorHandler("Error in onProgress callback", e);
  63597. }
  63598. } : undefined;
  63599. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  63600. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  63601. if (onSuccess) {
  63602. try {
  63603. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  63604. }
  63605. catch (e) {
  63606. errorHandler("Error in onSuccess callback", e);
  63607. }
  63608. }
  63609. scene._removePendingData(loadingToken);
  63610. };
  63611. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63612. if (plugin.rewriteRootURL) {
  63613. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  63614. }
  63615. if (sceneFilename === "") {
  63616. if (sceneFilename === "") {
  63617. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63618. }
  63619. }
  63620. if (plugin.importMesh) {
  63621. var syncedPlugin = plugin;
  63622. var meshes = new Array();
  63623. var particleSystems = new Array();
  63624. var skeletons = new Array();
  63625. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  63626. return;
  63627. }
  63628. scene.loadingPluginName = plugin.name;
  63629. successHandler(meshes, particleSystems, skeletons, []);
  63630. }
  63631. else {
  63632. var asyncedPlugin = plugin;
  63633. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  63634. scene.loadingPluginName = plugin.name;
  63635. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  63636. }).catch(function (error) {
  63637. errorHandler(error.message, error);
  63638. });
  63639. }
  63640. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63641. };
  63642. /**
  63643. * Import meshes into a scene
  63644. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  63645. * @param rootUrl a string that defines the root url for scene and resources
  63646. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63647. * @param scene the instance of BABYLON.Scene to append to
  63648. * @param onProgress a callback with a progress event for each file being loaded
  63649. * @param pluginExtension the extension used to determine the plugin
  63650. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  63651. */
  63652. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63653. if (onProgress === void 0) { onProgress = null; }
  63654. if (pluginExtension === void 0) { pluginExtension = null; }
  63655. return new Promise(function (resolve, reject) {
  63656. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  63657. resolve({
  63658. meshes: meshes,
  63659. particleSystems: particleSystems,
  63660. skeletons: skeletons,
  63661. animationGroups: animationGroups
  63662. });
  63663. }, onProgress, function (scene, message, exception) {
  63664. reject(exception || new Error(message));
  63665. });
  63666. });
  63667. };
  63668. /**
  63669. * Load a scene
  63670. * @param rootUrl a string that defines the root url for scene and resources
  63671. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63672. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63673. * @param onSuccess a callback with the scene when import succeeds
  63674. * @param onProgress a callback with a progress event for each file being loaded
  63675. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63676. * @param pluginExtension the extension used to determine the plugin
  63677. * @returns The loaded plugin
  63678. */
  63679. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  63680. if (onSuccess === void 0) { onSuccess = null; }
  63681. if (onProgress === void 0) { onProgress = null; }
  63682. if (onError === void 0) { onError = null; }
  63683. if (pluginExtension === void 0) { pluginExtension = null; }
  63684. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  63685. };
  63686. /**
  63687. * Load a scene
  63688. * @param rootUrl a string that defines the root url for scene and resources
  63689. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63690. * @param engine is the instance of BABYLON.Engine to use to create the scene
  63691. * @param onProgress a callback with a progress event for each file being loaded
  63692. * @param pluginExtension the extension used to determine the plugin
  63693. * @returns The loaded scene
  63694. */
  63695. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  63696. if (onProgress === void 0) { onProgress = null; }
  63697. if (pluginExtension === void 0) { pluginExtension = null; }
  63698. return new Promise(function (resolve, reject) {
  63699. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  63700. resolve(scene);
  63701. }, onProgress, function (scene, message, exception) {
  63702. reject(exception || new Error(message));
  63703. }, pluginExtension);
  63704. });
  63705. };
  63706. /**
  63707. * Append a scene
  63708. * @param rootUrl a string that defines the root url for scene and resources
  63709. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63710. * @param scene is the instance of BABYLON.Scene to append to
  63711. * @param onSuccess a callback with the scene when import succeeds
  63712. * @param onProgress a callback with a progress event for each file being loaded
  63713. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63714. * @param pluginExtension the extension used to determine the plugin
  63715. * @returns The loaded plugin
  63716. */
  63717. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63718. if (onSuccess === void 0) { onSuccess = null; }
  63719. if (onProgress === void 0) { onProgress = null; }
  63720. if (onError === void 0) { onError = null; }
  63721. if (pluginExtension === void 0) { pluginExtension = null; }
  63722. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63723. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63724. return null;
  63725. }
  63726. if (SceneLoader.ShowLoadingScreen) {
  63727. scene.getEngine().displayLoadingUI();
  63728. }
  63729. var loadingToken = {};
  63730. scene._addPendingData(loadingToken);
  63731. var disposeHandler = function () {
  63732. scene._removePendingData(loadingToken);
  63733. scene.getEngine().hideLoadingUI();
  63734. };
  63735. var errorHandler = function (message, exception) {
  63736. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63737. if (onError) {
  63738. onError(scene, errorMessage, exception);
  63739. }
  63740. else {
  63741. BABYLON.Tools.Error(errorMessage);
  63742. // should the exception be thrown?
  63743. }
  63744. disposeHandler();
  63745. };
  63746. var progressHandler = onProgress ? function (event) {
  63747. try {
  63748. onProgress(event);
  63749. }
  63750. catch (e) {
  63751. errorHandler("Error in onProgress callback", e);
  63752. }
  63753. } : undefined;
  63754. var successHandler = function () {
  63755. if (onSuccess) {
  63756. try {
  63757. onSuccess(scene);
  63758. }
  63759. catch (e) {
  63760. errorHandler("Error in onSuccess callback", e);
  63761. }
  63762. }
  63763. scene._removePendingData(loadingToken);
  63764. };
  63765. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63766. if (sceneFilename === "") {
  63767. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  63768. }
  63769. if (plugin.load) {
  63770. var syncedPlugin = plugin;
  63771. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  63772. return;
  63773. }
  63774. scene.loadingPluginName = plugin.name;
  63775. successHandler();
  63776. }
  63777. else {
  63778. var asyncedPlugin = plugin;
  63779. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63780. scene.loadingPluginName = plugin.name;
  63781. successHandler();
  63782. }).catch(function (error) {
  63783. errorHandler(error.message, error);
  63784. });
  63785. }
  63786. if (SceneLoader.ShowLoadingScreen) {
  63787. scene.executeWhenReady(function () {
  63788. scene.getEngine().hideLoadingUI();
  63789. });
  63790. }
  63791. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63792. };
  63793. /**
  63794. * Append a scene
  63795. * @param rootUrl a string that defines the root url for scene and resources
  63796. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63797. * @param scene is the instance of BABYLON.Scene to append to
  63798. * @param onProgress a callback with a progress event for each file being loaded
  63799. * @param pluginExtension the extension used to determine the plugin
  63800. * @returns The given scene
  63801. */
  63802. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63803. if (onProgress === void 0) { onProgress = null; }
  63804. if (pluginExtension === void 0) { pluginExtension = null; }
  63805. return new Promise(function (resolve, reject) {
  63806. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63807. resolve(scene);
  63808. }, onProgress, function (scene, message, exception) {
  63809. reject(exception || new Error(message));
  63810. }, pluginExtension);
  63811. });
  63812. };
  63813. /**
  63814. * Load a scene into an asset container
  63815. * @param rootUrl a string that defines the root url for scene and resources
  63816. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63817. * @param scene is the instance of BABYLON.Scene to append to
  63818. * @param onSuccess a callback with the scene when import succeeds
  63819. * @param onProgress a callback with a progress event for each file being loaded
  63820. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63821. * @param pluginExtension the extension used to determine the plugin
  63822. * @returns The loaded plugin
  63823. */
  63824. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63825. if (onSuccess === void 0) { onSuccess = null; }
  63826. if (onProgress === void 0) { onProgress = null; }
  63827. if (onError === void 0) { onError = null; }
  63828. if (pluginExtension === void 0) { pluginExtension = null; }
  63829. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63830. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63831. return null;
  63832. }
  63833. var loadingToken = {};
  63834. scene._addPendingData(loadingToken);
  63835. var disposeHandler = function () {
  63836. scene._removePendingData(loadingToken);
  63837. };
  63838. var errorHandler = function (message, exception) {
  63839. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63840. if (onError) {
  63841. onError(scene, errorMessage, exception);
  63842. }
  63843. else {
  63844. BABYLON.Tools.Error(errorMessage);
  63845. // should the exception be thrown?
  63846. }
  63847. disposeHandler();
  63848. };
  63849. var progressHandler = onProgress ? function (event) {
  63850. try {
  63851. onProgress(event);
  63852. }
  63853. catch (e) {
  63854. errorHandler("Error in onProgress callback", e);
  63855. }
  63856. } : undefined;
  63857. var successHandler = function (assets) {
  63858. if (onSuccess) {
  63859. try {
  63860. onSuccess(assets);
  63861. }
  63862. catch (e) {
  63863. errorHandler("Error in onSuccess callback", e);
  63864. }
  63865. }
  63866. scene._removePendingData(loadingToken);
  63867. };
  63868. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63869. if (plugin.loadAssetContainer) {
  63870. var syncedPlugin = plugin;
  63871. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63872. if (!assetContainer) {
  63873. return;
  63874. }
  63875. scene.loadingPluginName = plugin.name;
  63876. successHandler(assetContainer);
  63877. }
  63878. else if (plugin.loadAssetContainerAsync) {
  63879. var asyncedPlugin = plugin;
  63880. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63881. scene.loadingPluginName = plugin.name;
  63882. successHandler(assetContainer);
  63883. }).catch(function (error) {
  63884. errorHandler(error.message, error);
  63885. });
  63886. }
  63887. else {
  63888. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63889. }
  63890. if (SceneLoader.ShowLoadingScreen) {
  63891. scene.executeWhenReady(function () {
  63892. scene.getEngine().hideLoadingUI();
  63893. });
  63894. }
  63895. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63896. };
  63897. /**
  63898. * Load a scene into an asset container
  63899. * @param rootUrl a string that defines the root url for scene and resources
  63900. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63901. * @param scene is the instance of BABYLON.Scene to append to
  63902. * @param onProgress a callback with a progress event for each file being loaded
  63903. * @param pluginExtension the extension used to determine the plugin
  63904. * @returns The loaded asset container
  63905. */
  63906. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63907. if (onProgress === void 0) { onProgress = null; }
  63908. if (pluginExtension === void 0) { pluginExtension = null; }
  63909. return new Promise(function (resolve, reject) {
  63910. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63911. resolve(assetContainer);
  63912. }, onProgress, function (scene, message, exception) {
  63913. reject(exception || new Error(message));
  63914. }, pluginExtension);
  63915. });
  63916. };
  63917. // Flags
  63918. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63919. SceneLoader._ShowLoadingScreen = true;
  63920. SceneLoader._CleanBoneMatrixWeights = false;
  63921. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63922. // Members
  63923. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63924. SceneLoader._registeredPlugins = {};
  63925. return SceneLoader;
  63926. }());
  63927. BABYLON.SceneLoader = SceneLoader;
  63928. ;
  63929. })(BABYLON || (BABYLON = {}));
  63930. //# sourceMappingURL=babylon.sceneLoader.js.map
  63931. "use strict";
  63932. var BABYLON;
  63933. (function (BABYLON) {
  63934. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63935. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63936. var parsedMaterial = parsedData.materials[index];
  63937. if (parsedMaterial.id === id) {
  63938. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63939. }
  63940. }
  63941. return null;
  63942. };
  63943. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63944. for (var i in names) {
  63945. if (mesh.name === names[i]) {
  63946. hierarchyIds.push(mesh.id);
  63947. return true;
  63948. }
  63949. }
  63950. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63951. hierarchyIds.push(mesh.id);
  63952. return true;
  63953. }
  63954. return false;
  63955. };
  63956. var logOperation = function (operation, producer) {
  63957. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63958. };
  63959. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63960. if (addToScene === void 0) { addToScene = false; }
  63961. var container = new BABYLON.AssetContainer(scene);
  63962. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63963. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63964. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63965. // and avoid problems with multiple concurrent .babylon loads.
  63966. var log = "importScene has failed JSON parse";
  63967. try {
  63968. var parsedData = JSON.parse(data);
  63969. log = "";
  63970. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63971. var index;
  63972. var cache;
  63973. // Lights
  63974. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63975. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63976. var parsedLight = parsedData.lights[index];
  63977. var light = BABYLON.Light.Parse(parsedLight, scene);
  63978. if (light) {
  63979. container.lights.push(light);
  63980. log += (index === 0 ? "\n\tLights:" : "");
  63981. log += "\n\t\t" + light.toString(fullDetails);
  63982. }
  63983. }
  63984. }
  63985. // Animations
  63986. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63987. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63988. var parsedAnimation = parsedData.animations[index];
  63989. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63990. scene.animations.push(animation);
  63991. container.animations.push(animation);
  63992. log += (index === 0 ? "\n\tAnimations:" : "");
  63993. log += "\n\t\t" + animation.toString(fullDetails);
  63994. }
  63995. }
  63996. // Materials
  63997. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63998. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63999. var parsedMaterial = parsedData.materials[index];
  64000. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  64001. container.materials.push(mat);
  64002. log += (index === 0 ? "\n\tMaterials:" : "");
  64003. log += "\n\t\t" + mat.toString(fullDetails);
  64004. }
  64005. }
  64006. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  64007. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  64008. var parsedMultiMaterial = parsedData.multiMaterials[index];
  64009. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  64010. container.multiMaterials.push(mmat);
  64011. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  64012. log += "\n\t\t" + mmat.toString(fullDetails);
  64013. }
  64014. }
  64015. // Morph targets
  64016. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  64017. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  64018. var managerData = _a[_i];
  64019. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  64020. }
  64021. }
  64022. // Skeletons
  64023. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  64024. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  64025. var parsedSkeleton = parsedData.skeletons[index];
  64026. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  64027. container.skeletons.push(skeleton);
  64028. log += (index === 0 ? "\n\tSkeletons:" : "");
  64029. log += "\n\t\t" + skeleton.toString(fullDetails);
  64030. }
  64031. }
  64032. // Geometries
  64033. var geometries = parsedData.geometries;
  64034. if (geometries !== undefined && geometries !== null) {
  64035. var addedGeometry = new Array();
  64036. // Boxes
  64037. var boxes = geometries.boxes;
  64038. if (boxes !== undefined && boxes !== null) {
  64039. for (index = 0, cache = boxes.length; index < cache; index++) {
  64040. var parsedBox = boxes[index];
  64041. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  64042. }
  64043. }
  64044. // Spheres
  64045. var spheres = geometries.spheres;
  64046. if (spheres !== undefined && spheres !== null) {
  64047. for (index = 0, cache = spheres.length; index < cache; index++) {
  64048. var parsedSphere = spheres[index];
  64049. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  64050. }
  64051. }
  64052. // Cylinders
  64053. var cylinders = geometries.cylinders;
  64054. if (cylinders !== undefined && cylinders !== null) {
  64055. for (index = 0, cache = cylinders.length; index < cache; index++) {
  64056. var parsedCylinder = cylinders[index];
  64057. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  64058. }
  64059. }
  64060. // Toruses
  64061. var toruses = geometries.toruses;
  64062. if (toruses !== undefined && toruses !== null) {
  64063. for (index = 0, cache = toruses.length; index < cache; index++) {
  64064. var parsedTorus = toruses[index];
  64065. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  64066. }
  64067. }
  64068. // Grounds
  64069. var grounds = geometries.grounds;
  64070. if (grounds !== undefined && grounds !== null) {
  64071. for (index = 0, cache = grounds.length; index < cache; index++) {
  64072. var parsedGround = grounds[index];
  64073. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  64074. }
  64075. }
  64076. // Planes
  64077. var planes = geometries.planes;
  64078. if (planes !== undefined && planes !== null) {
  64079. for (index = 0, cache = planes.length; index < cache; index++) {
  64080. var parsedPlane = planes[index];
  64081. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  64082. }
  64083. }
  64084. // TorusKnots
  64085. var torusKnots = geometries.torusKnots;
  64086. if (torusKnots !== undefined && torusKnots !== null) {
  64087. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  64088. var parsedTorusKnot = torusKnots[index];
  64089. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  64090. }
  64091. }
  64092. // VertexData
  64093. var vertexData = geometries.vertexData;
  64094. if (vertexData !== undefined && vertexData !== null) {
  64095. for (index = 0, cache = vertexData.length; index < cache; index++) {
  64096. var parsedVertexData = vertexData[index];
  64097. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  64098. }
  64099. }
  64100. addedGeometry.forEach(function (g) {
  64101. if (g) {
  64102. container.geometries.push(g);
  64103. }
  64104. });
  64105. }
  64106. // Transform nodes
  64107. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  64108. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  64109. var parsedTransformNode = parsedData.transformNodes[index];
  64110. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  64111. container.transformNodes.push(node);
  64112. }
  64113. }
  64114. // Meshes
  64115. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  64116. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  64117. var parsedMesh = parsedData.meshes[index];
  64118. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  64119. container.meshes.push(mesh);
  64120. log += (index === 0 ? "\n\tMeshes:" : "");
  64121. log += "\n\t\t" + mesh.toString(fullDetails);
  64122. }
  64123. }
  64124. // Cameras
  64125. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  64126. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  64127. var parsedCamera = parsedData.cameras[index];
  64128. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  64129. container.cameras.push(camera);
  64130. log += (index === 0 ? "\n\tCameras:" : "");
  64131. log += "\n\t\t" + camera.toString(fullDetails);
  64132. }
  64133. }
  64134. // Browsing all the graph to connect the dots
  64135. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  64136. var camera = scene.cameras[index];
  64137. if (camera._waitingParentId) {
  64138. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  64139. camera._waitingParentId = null;
  64140. }
  64141. }
  64142. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  64143. var light_1 = scene.lights[index];
  64144. if (light_1 && light_1._waitingParentId) {
  64145. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  64146. light_1._waitingParentId = null;
  64147. }
  64148. }
  64149. // Sounds
  64150. // TODO: add sound
  64151. var loadedSounds = [];
  64152. var loadedSound;
  64153. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  64154. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  64155. var parsedSound = parsedData.sounds[index];
  64156. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64157. if (!parsedSound.url)
  64158. parsedSound.url = parsedSound.name;
  64159. if (!loadedSounds[parsedSound.url]) {
  64160. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  64161. loadedSounds[parsedSound.url] = loadedSound;
  64162. container.sounds.push(loadedSound);
  64163. }
  64164. else {
  64165. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  64166. }
  64167. }
  64168. else {
  64169. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  64170. }
  64171. }
  64172. }
  64173. loadedSounds = [];
  64174. // Connect parents & children and parse actions
  64175. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  64176. var transformNode = scene.transformNodes[index];
  64177. if (transformNode._waitingParentId) {
  64178. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  64179. transformNode._waitingParentId = null;
  64180. }
  64181. }
  64182. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64183. var mesh = scene.meshes[index];
  64184. if (mesh._waitingParentId) {
  64185. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  64186. mesh._waitingParentId = null;
  64187. }
  64188. if (mesh._waitingActions) {
  64189. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  64190. mesh._waitingActions = null;
  64191. }
  64192. }
  64193. // freeze world matrix application
  64194. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64195. var currentMesh = scene.meshes[index];
  64196. if (currentMesh._waitingFreezeWorldMatrix) {
  64197. currentMesh.freezeWorldMatrix();
  64198. currentMesh._waitingFreezeWorldMatrix = null;
  64199. }
  64200. else {
  64201. currentMesh.computeWorldMatrix(true);
  64202. }
  64203. }
  64204. // Particles Systems
  64205. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  64206. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  64207. var parsedParticleSystem = parsedData.particleSystems[index];
  64208. if (parsedParticleSystem.activeParticleCount) {
  64209. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  64210. container.particleSystems.push(ps);
  64211. }
  64212. else {
  64213. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  64214. container.particleSystems.push(ps);
  64215. }
  64216. }
  64217. }
  64218. // Lens flares
  64219. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  64220. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  64221. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  64222. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  64223. container.lensFlareSystems.push(lf);
  64224. }
  64225. }
  64226. // Shadows
  64227. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  64228. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  64229. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  64230. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  64231. container.shadowGenerators.push(sg);
  64232. }
  64233. }
  64234. // Lights exclusions / inclusions
  64235. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  64236. var light_2 = scene.lights[index];
  64237. // Excluded check
  64238. if (light_2._excludedMeshesIds.length > 0) {
  64239. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  64240. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  64241. if (excludedMesh) {
  64242. light_2.excludedMeshes.push(excludedMesh);
  64243. }
  64244. }
  64245. light_2._excludedMeshesIds = [];
  64246. }
  64247. // Included check
  64248. if (light_2._includedOnlyMeshesIds.length > 0) {
  64249. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  64250. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  64251. if (includedOnlyMesh) {
  64252. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  64253. }
  64254. }
  64255. light_2._includedOnlyMeshesIds = [];
  64256. }
  64257. }
  64258. // Actions (scene)
  64259. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  64260. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  64261. }
  64262. if (!addToScene) {
  64263. container.removeAllFromScene();
  64264. }
  64265. }
  64266. catch (err) {
  64267. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  64268. if (onError) {
  64269. onError(msg, err);
  64270. }
  64271. else {
  64272. BABYLON.Tools.Log(msg);
  64273. throw err;
  64274. }
  64275. }
  64276. finally {
  64277. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  64278. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  64279. }
  64280. }
  64281. return container;
  64282. };
  64283. BABYLON.SceneLoader.RegisterPlugin({
  64284. name: "babylon.js",
  64285. extensions: ".babylon",
  64286. canDirectLoad: function (data) {
  64287. if (data.indexOf("babylon") !== -1) {
  64288. return true;
  64289. }
  64290. return false;
  64291. },
  64292. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  64293. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  64294. // when SceneLoader.debugLogging = true (default), or exception encountered.
  64295. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  64296. // and avoid problems with multiple concurrent .babylon loads.
  64297. var log = "importMesh has failed JSON parse";
  64298. try {
  64299. var parsedData = JSON.parse(data);
  64300. log = "";
  64301. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  64302. if (!meshesNames) {
  64303. meshesNames = null;
  64304. }
  64305. else if (!Array.isArray(meshesNames)) {
  64306. meshesNames = [meshesNames];
  64307. }
  64308. var hierarchyIds = new Array();
  64309. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  64310. var loadedSkeletonsIds = [];
  64311. var loadedMaterialsIds = [];
  64312. var index;
  64313. var cache;
  64314. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  64315. var parsedMesh = parsedData.meshes[index];
  64316. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  64317. if (meshesNames !== null) {
  64318. // Remove found mesh name from list.
  64319. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  64320. }
  64321. //Geometry?
  64322. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  64323. //does the file contain geometries?
  64324. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  64325. //find the correct geometry and add it to the scene
  64326. var found = false;
  64327. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  64328. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  64329. return;
  64330. }
  64331. else {
  64332. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  64333. if (parsedGeometryData.id === parsedMesh.geometryId) {
  64334. switch (geometryType) {
  64335. case "boxes":
  64336. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  64337. break;
  64338. case "spheres":
  64339. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  64340. break;
  64341. case "cylinders":
  64342. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  64343. break;
  64344. case "toruses":
  64345. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  64346. break;
  64347. case "grounds":
  64348. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  64349. break;
  64350. case "planes":
  64351. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  64352. break;
  64353. case "torusKnots":
  64354. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  64355. break;
  64356. case "vertexData":
  64357. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  64358. break;
  64359. }
  64360. found = true;
  64361. }
  64362. });
  64363. }
  64364. });
  64365. if (found === false) {
  64366. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  64367. }
  64368. }
  64369. }
  64370. // Material ?
  64371. if (parsedMesh.materialId) {
  64372. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  64373. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  64374. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  64375. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  64376. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  64377. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  64378. var subMatId = parsedMultiMaterial.materials[matIndex];
  64379. loadedMaterialsIds.push(subMatId);
  64380. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  64381. if (mat) {
  64382. log += "\n\tMaterial " + mat.toString(fullDetails);
  64383. }
  64384. }
  64385. loadedMaterialsIds.push(parsedMultiMaterial.id);
  64386. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  64387. if (mmat) {
  64388. materialFound = true;
  64389. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  64390. }
  64391. break;
  64392. }
  64393. }
  64394. }
  64395. if (materialFound === false) {
  64396. loadedMaterialsIds.push(parsedMesh.materialId);
  64397. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  64398. if (!mat) {
  64399. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  64400. }
  64401. else {
  64402. log += "\n\tMaterial " + mat.toString(fullDetails);
  64403. }
  64404. }
  64405. }
  64406. // Skeleton ?
  64407. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  64408. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  64409. if (skeletonAlreadyLoaded === false) {
  64410. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  64411. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  64412. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  64413. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  64414. skeletons.push(skeleton);
  64415. loadedSkeletonsIds.push(parsedSkeleton.id);
  64416. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  64417. }
  64418. }
  64419. }
  64420. }
  64421. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  64422. meshes.push(mesh);
  64423. log += "\n\tMesh " + mesh.toString(fullDetails);
  64424. }
  64425. }
  64426. // Connecting parents
  64427. var currentMesh;
  64428. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64429. currentMesh = scene.meshes[index];
  64430. if (currentMesh._waitingParentId) {
  64431. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  64432. currentMesh._waitingParentId = null;
  64433. }
  64434. }
  64435. // freeze and compute world matrix application
  64436. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  64437. currentMesh = scene.meshes[index];
  64438. if (currentMesh._waitingFreezeWorldMatrix) {
  64439. currentMesh.freezeWorldMatrix();
  64440. currentMesh._waitingFreezeWorldMatrix = null;
  64441. }
  64442. else {
  64443. currentMesh.computeWorldMatrix(true);
  64444. }
  64445. }
  64446. }
  64447. // Particles
  64448. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  64449. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  64450. var parsedParticleSystem = parsedData.particleSystems[index];
  64451. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  64452. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  64453. }
  64454. }
  64455. }
  64456. return true;
  64457. }
  64458. catch (err) {
  64459. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  64460. if (onError) {
  64461. onError(msg, err);
  64462. }
  64463. else {
  64464. BABYLON.Tools.Log(msg);
  64465. throw err;
  64466. }
  64467. }
  64468. finally {
  64469. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  64470. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  64471. }
  64472. }
  64473. return false;
  64474. },
  64475. load: function (scene, data, rootUrl, onError) {
  64476. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  64477. // when SceneLoader.debugLogging = true (default), or exception encountered.
  64478. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  64479. // and avoid problems with multiple concurrent .babylon loads.
  64480. var log = "importScene has failed JSON parse";
  64481. try {
  64482. var parsedData = JSON.parse(data);
  64483. log = "";
  64484. // Scene
  64485. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  64486. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  64487. }
  64488. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  64489. scene.autoClear = parsedData.autoClear;
  64490. }
  64491. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  64492. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  64493. }
  64494. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  64495. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  64496. }
  64497. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  64498. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  64499. }
  64500. // Fog
  64501. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  64502. scene.fogMode = parsedData.fogMode;
  64503. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  64504. scene.fogStart = parsedData.fogStart;
  64505. scene.fogEnd = parsedData.fogEnd;
  64506. scene.fogDensity = parsedData.fogDensity;
  64507. log += "\tFog mode for scene: ";
  64508. switch (scene.fogMode) {
  64509. // getters not compiling, so using hardcoded
  64510. case 1:
  64511. log += "exp\n";
  64512. break;
  64513. case 2:
  64514. log += "exp2\n";
  64515. break;
  64516. case 3:
  64517. log += "linear\n";
  64518. break;
  64519. }
  64520. }
  64521. //Physics
  64522. if (parsedData.physicsEnabled) {
  64523. var physicsPlugin;
  64524. if (parsedData.physicsEngine === "cannon") {
  64525. physicsPlugin = new BABYLON.CannonJSPlugin();
  64526. }
  64527. else if (parsedData.physicsEngine === "oimo") {
  64528. physicsPlugin = new BABYLON.OimoJSPlugin();
  64529. }
  64530. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  64531. //else - default engine, which is currently oimo
  64532. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  64533. scene.enablePhysics(physicsGravity, physicsPlugin);
  64534. }
  64535. // Metadata
  64536. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  64537. scene.metadata = parsedData.metadata;
  64538. }
  64539. //collisions, if defined. otherwise, default is true
  64540. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  64541. scene.collisionsEnabled = parsedData.collisionsEnabled;
  64542. }
  64543. scene.workerCollisions = !!parsedData.workerCollisions;
  64544. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  64545. if (!container) {
  64546. return false;
  64547. }
  64548. if (parsedData.autoAnimate) {
  64549. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  64550. }
  64551. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  64552. scene.setActiveCameraByID(parsedData.activeCameraID);
  64553. }
  64554. // Environment texture
  64555. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  64556. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  64557. if (parsedData.createDefaultSkybox === true) {
  64558. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  64559. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  64560. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  64561. }
  64562. }
  64563. // Finish
  64564. return true;
  64565. }
  64566. catch (err) {
  64567. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  64568. if (onError) {
  64569. onError(msg, err);
  64570. }
  64571. else {
  64572. BABYLON.Tools.Log(msg);
  64573. throw err;
  64574. }
  64575. }
  64576. finally {
  64577. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  64578. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  64579. }
  64580. }
  64581. return false;
  64582. },
  64583. loadAssetContainer: function (scene, data, rootUrl, onError) {
  64584. var container = loadAssetContainer(scene, data, rootUrl, onError);
  64585. return container;
  64586. }
  64587. });
  64588. })(BABYLON || (BABYLON = {}));
  64589. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  64590. "use strict";
  64591. var BABYLON;
  64592. (function (BABYLON) {
  64593. var FilesInput = /** @class */ (function () {
  64594. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  64595. this.onProcessFileCallback = function () { return true; };
  64596. this._engine = engine;
  64597. this._currentScene = scene;
  64598. this._sceneLoadedCallback = sceneLoadedCallback;
  64599. this._progressCallback = progressCallback;
  64600. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  64601. this._textureLoadingCallback = textureLoadingCallback;
  64602. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  64603. this._onReloadCallback = onReloadCallback;
  64604. this._errorCallback = errorCallback;
  64605. }
  64606. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  64607. var _this = this;
  64608. if (elementToMonitor) {
  64609. this._elementToMonitor = elementToMonitor;
  64610. this._dragEnterHandler = function (e) { _this.drag(e); };
  64611. this._dragOverHandler = function (e) { _this.drag(e); };
  64612. this._dropHandler = function (e) { _this.drop(e); };
  64613. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  64614. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  64615. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  64616. }
  64617. };
  64618. FilesInput.prototype.dispose = function () {
  64619. if (!this._elementToMonitor) {
  64620. return;
  64621. }
  64622. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  64623. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  64624. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  64625. };
  64626. FilesInput.prototype.renderFunction = function () {
  64627. if (this._additionalRenderLoopLogicCallback) {
  64628. this._additionalRenderLoopLogicCallback();
  64629. }
  64630. if (this._currentScene) {
  64631. if (this._textureLoadingCallback) {
  64632. var remaining = this._currentScene.getWaitingItemsCount();
  64633. if (remaining > 0) {
  64634. this._textureLoadingCallback(remaining);
  64635. }
  64636. }
  64637. this._currentScene.render();
  64638. }
  64639. };
  64640. FilesInput.prototype.drag = function (e) {
  64641. e.stopPropagation();
  64642. e.preventDefault();
  64643. };
  64644. FilesInput.prototype.drop = function (eventDrop) {
  64645. eventDrop.stopPropagation();
  64646. eventDrop.preventDefault();
  64647. this.loadFiles(eventDrop);
  64648. };
  64649. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  64650. var _this = this;
  64651. var reader = folder.createReader();
  64652. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  64653. reader.readEntries(function (entries) {
  64654. remaining.count += entries.length;
  64655. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  64656. var entry = entries_1[_i];
  64657. if (entry.isFile) {
  64658. entry.file(function (file) {
  64659. file.correctName = relativePath + file.name;
  64660. files.push(file);
  64661. if (--remaining.count === 0) {
  64662. callback();
  64663. }
  64664. });
  64665. }
  64666. else if (entry.isDirectory) {
  64667. _this._traverseFolder(entry, files, remaining, callback);
  64668. }
  64669. }
  64670. if (--remaining.count) {
  64671. callback();
  64672. }
  64673. });
  64674. };
  64675. FilesInput.prototype._processFiles = function (files) {
  64676. for (var i = 0; i < files.length; i++) {
  64677. var name = files[i].correctName.toLowerCase();
  64678. var extension = name.split('.').pop();
  64679. if (!this.onProcessFileCallback(files[i], name, extension)) {
  64680. continue;
  64681. }
  64682. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  64683. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  64684. this._sceneFileToLoad = files[i];
  64685. }
  64686. else {
  64687. FilesInput.FilesToLoad[name] = files[i];
  64688. }
  64689. }
  64690. };
  64691. FilesInput.prototype.loadFiles = function (event) {
  64692. var _this = this;
  64693. if (this._startingProcessingFilesCallback)
  64694. this._startingProcessingFilesCallback();
  64695. // Handling data transfer via drag'n'drop
  64696. if (event && event.dataTransfer && event.dataTransfer.files) {
  64697. this._filesToLoad = event.dataTransfer.files;
  64698. }
  64699. // Handling files from input files
  64700. if (event && event.target && event.target.files) {
  64701. this._filesToLoad = event.target.files;
  64702. }
  64703. if (this._filesToLoad && this._filesToLoad.length > 0) {
  64704. var files_1 = new Array();
  64705. var folders = [];
  64706. var items = event.dataTransfer ? event.dataTransfer.items : null;
  64707. for (var i = 0; i < this._filesToLoad.length; i++) {
  64708. var fileToLoad = this._filesToLoad[i];
  64709. var name_1 = fileToLoad.name.toLowerCase();
  64710. var entry = void 0;
  64711. fileToLoad.correctName = name_1;
  64712. if (items) {
  64713. var item = items[i];
  64714. if (item.getAsEntry) {
  64715. entry = item.getAsEntry();
  64716. }
  64717. else if (item.webkitGetAsEntry) {
  64718. entry = item.webkitGetAsEntry();
  64719. }
  64720. }
  64721. if (!entry) {
  64722. files_1.push(fileToLoad);
  64723. }
  64724. else {
  64725. if (entry.isDirectory) {
  64726. folders.push(entry);
  64727. }
  64728. else {
  64729. files_1.push(fileToLoad);
  64730. }
  64731. }
  64732. }
  64733. if (folders.length === 0) {
  64734. this._processFiles(files_1);
  64735. this._processReload();
  64736. }
  64737. else {
  64738. var remaining = { count: folders.length };
  64739. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  64740. var folder = folders_1[_i];
  64741. this._traverseFolder(folder, files_1, remaining, function () {
  64742. _this._processFiles(files_1);
  64743. if (remaining.count === 0) {
  64744. _this._processReload();
  64745. }
  64746. });
  64747. }
  64748. }
  64749. }
  64750. };
  64751. FilesInput.prototype._processReload = function () {
  64752. if (this._onReloadCallback) {
  64753. this._onReloadCallback(this._sceneFileToLoad);
  64754. }
  64755. else {
  64756. this.reload();
  64757. }
  64758. };
  64759. FilesInput.prototype.reload = function () {
  64760. var _this = this;
  64761. // If a scene file has been provided
  64762. if (this._sceneFileToLoad) {
  64763. if (this._currentScene) {
  64764. if (BABYLON.Tools.errorsCount > 0) {
  64765. BABYLON.Tools.ClearLogCache();
  64766. }
  64767. this._engine.stopRenderLoop();
  64768. this._currentScene.dispose();
  64769. }
  64770. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  64771. if (_this._progressCallback) {
  64772. _this._progressCallback(progress);
  64773. }
  64774. }).then(function (scene) {
  64775. _this._currentScene = scene;
  64776. if (_this._sceneLoadedCallback) {
  64777. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64778. }
  64779. // Wait for textures and shaders to be ready
  64780. _this._currentScene.executeWhenReady(function () {
  64781. _this._engine.runRenderLoop(function () {
  64782. _this.renderFunction();
  64783. });
  64784. });
  64785. }).catch(function (error) {
  64786. if (_this._errorCallback) {
  64787. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64788. }
  64789. });
  64790. }
  64791. else {
  64792. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64793. }
  64794. };
  64795. FilesInput.FilesToLoad = {};
  64796. return FilesInput;
  64797. }());
  64798. BABYLON.FilesInput = FilesInput;
  64799. })(BABYLON || (BABYLON = {}));
  64800. //# sourceMappingURL=babylon.filesInput.js.map
  64801. "use strict";
  64802. var BABYLON;
  64803. (function (BABYLON) {
  64804. /**
  64805. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64806. * The underlying implementation relies on an associative array to ensure the best performances.
  64807. * The value can be anything including 'null' but except 'undefined'
  64808. */
  64809. var StringDictionary = /** @class */ (function () {
  64810. function StringDictionary() {
  64811. this._count = 0;
  64812. this._data = {};
  64813. }
  64814. /**
  64815. * This will clear this dictionary and copy the content from the 'source' one.
  64816. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64817. * @param source the dictionary to take the content from and copy to this dictionary
  64818. */
  64819. StringDictionary.prototype.copyFrom = function (source) {
  64820. var _this = this;
  64821. this.clear();
  64822. source.forEach(function (t, v) { return _this.add(t, v); });
  64823. };
  64824. /**
  64825. * Get a value based from its key
  64826. * @param key the given key to get the matching value from
  64827. * @return the value if found, otherwise undefined is returned
  64828. */
  64829. StringDictionary.prototype.get = function (key) {
  64830. var val = this._data[key];
  64831. if (val !== undefined) {
  64832. return val;
  64833. }
  64834. return undefined;
  64835. };
  64836. /**
  64837. * Get a value from its key or add it if it doesn't exist.
  64838. * This method will ensure you that a given key/data will be present in the dictionary.
  64839. * @param key the given key to get the matching value from
  64840. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64841. * The factory will only be invoked if there's no data for the given key.
  64842. * @return the value corresponding to the key.
  64843. */
  64844. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64845. var val = this.get(key);
  64846. if (val !== undefined) {
  64847. return val;
  64848. }
  64849. val = factory(key);
  64850. if (val) {
  64851. this.add(key, val);
  64852. }
  64853. return val;
  64854. };
  64855. /**
  64856. * Get a value from its key if present in the dictionary otherwise add it
  64857. * @param key the key to get the value from
  64858. * @param val if there's no such key/value pair in the dictionary add it with this value
  64859. * @return the value corresponding to the key
  64860. */
  64861. StringDictionary.prototype.getOrAdd = function (key, val) {
  64862. var curVal = this.get(key);
  64863. if (curVal !== undefined) {
  64864. return curVal;
  64865. }
  64866. this.add(key, val);
  64867. return val;
  64868. };
  64869. /**
  64870. * Check if there's a given key in the dictionary
  64871. * @param key the key to check for
  64872. * @return true if the key is present, false otherwise
  64873. */
  64874. StringDictionary.prototype.contains = function (key) {
  64875. return this._data[key] !== undefined;
  64876. };
  64877. /**
  64878. * Add a new key and its corresponding value
  64879. * @param key the key to add
  64880. * @param value the value corresponding to the key
  64881. * @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
  64882. */
  64883. StringDictionary.prototype.add = function (key, value) {
  64884. if (this._data[key] !== undefined) {
  64885. return false;
  64886. }
  64887. this._data[key] = value;
  64888. ++this._count;
  64889. return true;
  64890. };
  64891. StringDictionary.prototype.set = function (key, value) {
  64892. if (this._data[key] === undefined) {
  64893. return false;
  64894. }
  64895. this._data[key] = value;
  64896. return true;
  64897. };
  64898. /**
  64899. * Get the element of the given key and remove it from the dictionary
  64900. * @param key
  64901. */
  64902. StringDictionary.prototype.getAndRemove = function (key) {
  64903. var val = this.get(key);
  64904. if (val !== undefined) {
  64905. delete this._data[key];
  64906. --this._count;
  64907. return val;
  64908. }
  64909. return null;
  64910. };
  64911. /**
  64912. * Remove a key/value from the dictionary.
  64913. * @param key the key to remove
  64914. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64915. */
  64916. StringDictionary.prototype.remove = function (key) {
  64917. if (this.contains(key)) {
  64918. delete this._data[key];
  64919. --this._count;
  64920. return true;
  64921. }
  64922. return false;
  64923. };
  64924. /**
  64925. * Clear the whole content of the dictionary
  64926. */
  64927. StringDictionary.prototype.clear = function () {
  64928. this._data = {};
  64929. this._count = 0;
  64930. };
  64931. Object.defineProperty(StringDictionary.prototype, "count", {
  64932. get: function () {
  64933. return this._count;
  64934. },
  64935. enumerable: true,
  64936. configurable: true
  64937. });
  64938. /**
  64939. * Execute a callback on each key/val of the dictionary.
  64940. * Note that you can remove any element in this dictionary in the callback implementation
  64941. * @param callback the callback to execute on a given key/value pair
  64942. */
  64943. StringDictionary.prototype.forEach = function (callback) {
  64944. for (var cur in this._data) {
  64945. var val = this._data[cur];
  64946. callback(cur, val);
  64947. }
  64948. };
  64949. /**
  64950. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64951. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64952. * Note that you can remove any element in this dictionary in the callback implementation
  64953. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64954. */
  64955. StringDictionary.prototype.first = function (callback) {
  64956. for (var cur in this._data) {
  64957. var val = this._data[cur];
  64958. var res = callback(cur, val);
  64959. if (res) {
  64960. return res;
  64961. }
  64962. }
  64963. return null;
  64964. };
  64965. return StringDictionary;
  64966. }());
  64967. BABYLON.StringDictionary = StringDictionary;
  64968. })(BABYLON || (BABYLON = {}));
  64969. //# sourceMappingURL=babylon.stringDictionary.js.map
  64970. "use strict";
  64971. var BABYLON;
  64972. (function (BABYLON) {
  64973. var Tags = /** @class */ (function () {
  64974. function Tags() {
  64975. }
  64976. Tags.EnableFor = function (obj) {
  64977. obj._tags = obj._tags || {};
  64978. obj.hasTags = function () {
  64979. return Tags.HasTags(obj);
  64980. };
  64981. obj.addTags = function (tagsString) {
  64982. return Tags.AddTagsTo(obj, tagsString);
  64983. };
  64984. obj.removeTags = function (tagsString) {
  64985. return Tags.RemoveTagsFrom(obj, tagsString);
  64986. };
  64987. obj.matchesTagsQuery = function (tagsQuery) {
  64988. return Tags.MatchesQuery(obj, tagsQuery);
  64989. };
  64990. };
  64991. Tags.DisableFor = function (obj) {
  64992. delete obj._tags;
  64993. delete obj.hasTags;
  64994. delete obj.addTags;
  64995. delete obj.removeTags;
  64996. delete obj.matchesTagsQuery;
  64997. };
  64998. Tags.HasTags = function (obj) {
  64999. if (!obj._tags) {
  65000. return false;
  65001. }
  65002. return !BABYLON.Tools.IsEmpty(obj._tags);
  65003. };
  65004. Tags.GetTags = function (obj, asString) {
  65005. if (asString === void 0) { asString = true; }
  65006. if (!obj._tags) {
  65007. return null;
  65008. }
  65009. if (asString) {
  65010. var tagsArray = [];
  65011. for (var tag in obj._tags) {
  65012. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  65013. tagsArray.push(tag);
  65014. }
  65015. }
  65016. return tagsArray.join(" ");
  65017. }
  65018. else {
  65019. return obj._tags;
  65020. }
  65021. };
  65022. // the tags 'true' and 'false' are reserved and cannot be used as tags
  65023. // a tag cannot start with '||', '&&', and '!'
  65024. // it cannot contain whitespaces
  65025. Tags.AddTagsTo = function (obj, tagsString) {
  65026. if (!tagsString) {
  65027. return;
  65028. }
  65029. if (typeof tagsString !== "string") {
  65030. return;
  65031. }
  65032. var tags = tagsString.split(" ");
  65033. tags.forEach(function (tag, index, array) {
  65034. Tags._AddTagTo(obj, tag);
  65035. });
  65036. };
  65037. Tags._AddTagTo = function (obj, tag) {
  65038. tag = tag.trim();
  65039. if (tag === "" || tag === "true" || tag === "false") {
  65040. return;
  65041. }
  65042. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  65043. return;
  65044. }
  65045. Tags.EnableFor(obj);
  65046. obj._tags[tag] = true;
  65047. };
  65048. Tags.RemoveTagsFrom = function (obj, tagsString) {
  65049. if (!Tags.HasTags(obj)) {
  65050. return;
  65051. }
  65052. var tags = tagsString.split(" ");
  65053. for (var t in tags) {
  65054. Tags._RemoveTagFrom(obj, tags[t]);
  65055. }
  65056. };
  65057. Tags._RemoveTagFrom = function (obj, tag) {
  65058. delete obj._tags[tag];
  65059. };
  65060. Tags.MatchesQuery = function (obj, tagsQuery) {
  65061. if (tagsQuery === undefined) {
  65062. return true;
  65063. }
  65064. if (tagsQuery === "") {
  65065. return Tags.HasTags(obj);
  65066. }
  65067. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  65068. };
  65069. return Tags;
  65070. }());
  65071. BABYLON.Tags = Tags;
  65072. })(BABYLON || (BABYLON = {}));
  65073. //# sourceMappingURL=babylon.tags.js.map
  65074. "use strict";
  65075. var BABYLON;
  65076. (function (BABYLON) {
  65077. var AndOrNotEvaluator = /** @class */ (function () {
  65078. function AndOrNotEvaluator() {
  65079. }
  65080. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  65081. if (!query.match(/\([^\(\)]*\)/g)) {
  65082. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  65083. }
  65084. else {
  65085. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  65086. // remove parenthesis
  65087. r = r.slice(1, r.length - 1);
  65088. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  65089. });
  65090. }
  65091. if (query === "true") {
  65092. return true;
  65093. }
  65094. if (query === "false") {
  65095. return false;
  65096. }
  65097. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  65098. };
  65099. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  65100. evaluateCallback = evaluateCallback || (function (r) {
  65101. return r === "true" ? true : false;
  65102. });
  65103. var result;
  65104. var or = parenthesisContent.split("||");
  65105. for (var i in or) {
  65106. if (or.hasOwnProperty(i)) {
  65107. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  65108. var and = ori.split("&&");
  65109. if (and.length > 1) {
  65110. for (var j = 0; j < and.length; ++j) {
  65111. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  65112. if (andj !== "true" && andj !== "false") {
  65113. if (andj[0] === "!") {
  65114. result = !evaluateCallback(andj.substring(1));
  65115. }
  65116. else {
  65117. result = evaluateCallback(andj);
  65118. }
  65119. }
  65120. else {
  65121. result = andj === "true" ? true : false;
  65122. }
  65123. if (!result) {
  65124. ori = "false";
  65125. break;
  65126. }
  65127. }
  65128. }
  65129. if (result || ori === "true") {
  65130. result = true;
  65131. break;
  65132. }
  65133. // result equals false (or undefined)
  65134. if (ori !== "true" && ori !== "false") {
  65135. if (ori[0] === "!") {
  65136. result = !evaluateCallback(ori.substring(1));
  65137. }
  65138. else {
  65139. result = evaluateCallback(ori);
  65140. }
  65141. }
  65142. else {
  65143. result = ori === "true" ? true : false;
  65144. }
  65145. }
  65146. }
  65147. // the whole parenthesis scope is replaced by 'true' or 'false'
  65148. return result ? "true" : "false";
  65149. };
  65150. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  65151. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  65152. // remove whitespaces
  65153. r = r.replace(/[\s]/g, function () { return ""; });
  65154. return r.length % 2 ? "!" : "";
  65155. });
  65156. booleanString = booleanString.trim();
  65157. if (booleanString === "!true") {
  65158. booleanString = "false";
  65159. }
  65160. else if (booleanString === "!false") {
  65161. booleanString = "true";
  65162. }
  65163. return booleanString;
  65164. };
  65165. return AndOrNotEvaluator;
  65166. }());
  65167. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  65168. })(BABYLON || (BABYLON = {}));
  65169. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  65170. "use strict";
  65171. var BABYLON;
  65172. (function (BABYLON) {
  65173. var Database = /** @class */ (function () {
  65174. function Database(urlToScene, callbackManifestChecked) {
  65175. // Handling various flavors of prefixed version of IndexedDB
  65176. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  65177. this.callbackManifestChecked = callbackManifestChecked;
  65178. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  65179. this.db = null;
  65180. this._enableSceneOffline = false;
  65181. this._enableTexturesOffline = false;
  65182. this.manifestVersionFound = 0;
  65183. this.mustUpdateRessources = false;
  65184. this.hasReachedQuota = false;
  65185. if (!Database.IDBStorageEnabled) {
  65186. this.callbackManifestChecked(true);
  65187. }
  65188. else {
  65189. this.checkManifestFile();
  65190. }
  65191. }
  65192. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  65193. get: function () {
  65194. return this._enableSceneOffline;
  65195. },
  65196. enumerable: true,
  65197. configurable: true
  65198. });
  65199. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  65200. get: function () {
  65201. return this._enableTexturesOffline;
  65202. },
  65203. enumerable: true,
  65204. configurable: true
  65205. });
  65206. Database.prototype.checkManifestFile = function () {
  65207. var _this = this;
  65208. var noManifestFile = function () {
  65209. _this._enableSceneOffline = false;
  65210. _this._enableTexturesOffline = false;
  65211. _this.callbackManifestChecked(false);
  65212. };
  65213. var timeStampUsed = false;
  65214. var manifestURL = this.currentSceneUrl + ".manifest";
  65215. var xhr = new XMLHttpRequest();
  65216. if (navigator.onLine) {
  65217. // Adding a timestamp to by-pass browsers' cache
  65218. timeStampUsed = true;
  65219. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  65220. }
  65221. xhr.open("GET", manifestURL, true);
  65222. xhr.addEventListener("load", function () {
  65223. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65224. try {
  65225. var manifestFile = JSON.parse(xhr.response);
  65226. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  65227. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  65228. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  65229. _this.manifestVersionFound = manifestFile.version;
  65230. }
  65231. if (_this.callbackManifestChecked) {
  65232. _this.callbackManifestChecked(true);
  65233. }
  65234. }
  65235. catch (ex) {
  65236. noManifestFile();
  65237. }
  65238. }
  65239. else {
  65240. noManifestFile();
  65241. }
  65242. }, false);
  65243. xhr.addEventListener("error", function (event) {
  65244. if (timeStampUsed) {
  65245. timeStampUsed = false;
  65246. // Let's retry without the timeStamp
  65247. // It could fail when coupled with HTML5 Offline API
  65248. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  65249. xhr.open("GET", retryManifestURL, true);
  65250. xhr.send();
  65251. }
  65252. else {
  65253. noManifestFile();
  65254. }
  65255. }, false);
  65256. try {
  65257. xhr.send();
  65258. }
  65259. catch (ex) {
  65260. BABYLON.Tools.Error("Error on XHR send request.");
  65261. this.callbackManifestChecked(false);
  65262. }
  65263. };
  65264. Database.prototype.openAsync = function (successCallback, errorCallback) {
  65265. var _this = this;
  65266. var handleError = function () {
  65267. _this.isSupported = false;
  65268. if (errorCallback)
  65269. errorCallback();
  65270. };
  65271. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  65272. // Your browser doesn't support IndexedDB
  65273. this.isSupported = false;
  65274. if (errorCallback)
  65275. errorCallback();
  65276. }
  65277. else {
  65278. // If the DB hasn't been opened or created yet
  65279. if (!this.db) {
  65280. this.hasReachedQuota = false;
  65281. this.isSupported = true;
  65282. var request = this.idbFactory.open("babylonjs", 1);
  65283. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  65284. request.onerror = function (event) {
  65285. handleError();
  65286. };
  65287. // executes when a version change transaction cannot complete due to other active transactions
  65288. request.onblocked = function (event) {
  65289. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  65290. handleError();
  65291. };
  65292. // DB has been opened successfully
  65293. request.onsuccess = function (event) {
  65294. _this.db = request.result;
  65295. successCallback();
  65296. };
  65297. // Initialization of the DB. Creating Scenes & Textures stores
  65298. request.onupgradeneeded = function (event) {
  65299. _this.db = (event.target).result;
  65300. if (_this.db) {
  65301. try {
  65302. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  65303. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  65304. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  65305. }
  65306. catch (ex) {
  65307. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  65308. handleError();
  65309. }
  65310. }
  65311. };
  65312. }
  65313. else {
  65314. if (successCallback)
  65315. successCallback();
  65316. }
  65317. }
  65318. };
  65319. Database.prototype.loadImageFromDB = function (url, image) {
  65320. var _this = this;
  65321. var completeURL = Database.ReturnFullUrlLocation(url);
  65322. var saveAndLoadImage = function () {
  65323. if (!_this.hasReachedQuota && _this.db !== null) {
  65324. // the texture is not yet in the DB, let's try to save it
  65325. _this._saveImageIntoDBAsync(completeURL, image);
  65326. }
  65327. else {
  65328. image.src = url;
  65329. }
  65330. };
  65331. if (!this.mustUpdateRessources) {
  65332. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  65333. }
  65334. else {
  65335. saveAndLoadImage();
  65336. }
  65337. };
  65338. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  65339. if (this.isSupported && this.db !== null) {
  65340. var texture;
  65341. var transaction = this.db.transaction(["textures"]);
  65342. transaction.onabort = function (event) {
  65343. image.src = url;
  65344. };
  65345. transaction.oncomplete = function (event) {
  65346. var blobTextureURL;
  65347. if (texture) {
  65348. var URL = window.URL || window.webkitURL;
  65349. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  65350. image.onerror = function () {
  65351. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  65352. image.src = url;
  65353. };
  65354. image.src = blobTextureURL;
  65355. }
  65356. else {
  65357. notInDBCallback();
  65358. }
  65359. };
  65360. var getRequest = transaction.objectStore("textures").get(url);
  65361. getRequest.onsuccess = function (event) {
  65362. texture = (event.target).result;
  65363. };
  65364. getRequest.onerror = function (event) {
  65365. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  65366. image.src = url;
  65367. };
  65368. }
  65369. else {
  65370. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65371. image.src = url;
  65372. }
  65373. };
  65374. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  65375. var _this = this;
  65376. if (this.isSupported) {
  65377. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  65378. var generateBlobUrl = function () {
  65379. var blobTextureURL;
  65380. if (blob) {
  65381. var URL = window.URL || window.webkitURL;
  65382. try {
  65383. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  65384. }
  65385. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  65386. catch (ex) {
  65387. blobTextureURL = URL.createObjectURL(blob);
  65388. }
  65389. }
  65390. if (blobTextureURL) {
  65391. image.src = blobTextureURL;
  65392. }
  65393. };
  65394. if (Database.IsUASupportingBlobStorage) {
  65395. var xhr = new XMLHttpRequest(), blob;
  65396. xhr.open("GET", url, true);
  65397. xhr.responseType = "blob";
  65398. xhr.addEventListener("load", function () {
  65399. if (xhr.status === 200 && _this.db) {
  65400. // Blob as response (XHR2)
  65401. blob = xhr.response;
  65402. var transaction = _this.db.transaction(["textures"], "readwrite");
  65403. // the transaction could abort because of a QuotaExceededError error
  65404. transaction.onabort = function (event) {
  65405. try {
  65406. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  65407. var srcElement = (event.srcElement || event.target);
  65408. var error = srcElement.error;
  65409. if (error && error.name === "QuotaExceededError") {
  65410. _this.hasReachedQuota = true;
  65411. }
  65412. }
  65413. catch (ex) { }
  65414. generateBlobUrl();
  65415. };
  65416. transaction.oncomplete = function (event) {
  65417. generateBlobUrl();
  65418. };
  65419. var newTexture = { textureUrl: url, data: blob };
  65420. try {
  65421. // Put the blob into the dabase
  65422. var addRequest = transaction.objectStore("textures").put(newTexture);
  65423. addRequest.onsuccess = function (event) {
  65424. };
  65425. addRequest.onerror = function (event) {
  65426. generateBlobUrl();
  65427. };
  65428. }
  65429. catch (ex) {
  65430. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  65431. if (ex.code === 25) {
  65432. Database.IsUASupportingBlobStorage = false;
  65433. }
  65434. image.src = url;
  65435. }
  65436. }
  65437. else {
  65438. image.src = url;
  65439. }
  65440. }, false);
  65441. xhr.addEventListener("error", function (event) {
  65442. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  65443. image.src = url;
  65444. }, false);
  65445. xhr.send();
  65446. }
  65447. else {
  65448. image.src = url;
  65449. }
  65450. }
  65451. else {
  65452. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65453. image.src = url;
  65454. }
  65455. };
  65456. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  65457. var _this = this;
  65458. var updateVersion = function () {
  65459. // the version is not yet in the DB or we need to update it
  65460. _this._saveVersionIntoDBAsync(url, versionLoaded);
  65461. };
  65462. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  65463. };
  65464. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  65465. var _this = this;
  65466. if (this.isSupported && this.db) {
  65467. var version;
  65468. try {
  65469. var transaction = this.db.transaction(["versions"]);
  65470. transaction.oncomplete = function (event) {
  65471. if (version) {
  65472. // If the version in the JSON file is > than the version in DB
  65473. if (_this.manifestVersionFound > version.data) {
  65474. _this.mustUpdateRessources = true;
  65475. updateInDBCallback();
  65476. }
  65477. else {
  65478. callback(version.data);
  65479. }
  65480. }
  65481. else {
  65482. _this.mustUpdateRessources = true;
  65483. updateInDBCallback();
  65484. }
  65485. };
  65486. transaction.onabort = function (event) {
  65487. callback(-1);
  65488. };
  65489. var getRequest = transaction.objectStore("versions").get(url);
  65490. getRequest.onsuccess = function (event) {
  65491. version = (event.target).result;
  65492. };
  65493. getRequest.onerror = function (event) {
  65494. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  65495. callback(-1);
  65496. };
  65497. }
  65498. catch (ex) {
  65499. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  65500. callback(-1);
  65501. }
  65502. }
  65503. else {
  65504. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65505. callback(-1);
  65506. }
  65507. };
  65508. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  65509. var _this = this;
  65510. if (this.isSupported && !this.hasReachedQuota && this.db) {
  65511. try {
  65512. // Open a transaction to the database
  65513. var transaction = this.db.transaction(["versions"], "readwrite");
  65514. // the transaction could abort because of a QuotaExceededError error
  65515. transaction.onabort = function (event) {
  65516. try {
  65517. var error = event.srcElement['error'];
  65518. if (error && error.name === "QuotaExceededError") {
  65519. _this.hasReachedQuota = true;
  65520. }
  65521. }
  65522. catch (ex) { }
  65523. callback(-1);
  65524. };
  65525. transaction.oncomplete = function (event) {
  65526. callback(_this.manifestVersionFound);
  65527. };
  65528. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  65529. // Put the scene into the database
  65530. var addRequest = transaction.objectStore("versions").put(newVersion);
  65531. addRequest.onsuccess = function (event) {
  65532. };
  65533. addRequest.onerror = function (event) {
  65534. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  65535. };
  65536. }
  65537. catch (ex) {
  65538. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  65539. callback(-1);
  65540. }
  65541. }
  65542. else {
  65543. callback(-1);
  65544. }
  65545. };
  65546. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  65547. var _this = this;
  65548. var completeUrl = Database.ReturnFullUrlLocation(url);
  65549. var saveAndLoadFile = function () {
  65550. // the scene is not yet in the DB, let's try to save it
  65551. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  65552. };
  65553. this._checkVersionFromDB(completeUrl, function (version) {
  65554. if (version !== -1) {
  65555. if (!_this.mustUpdateRessources) {
  65556. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  65557. }
  65558. else {
  65559. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  65560. }
  65561. }
  65562. else {
  65563. if (errorCallback) {
  65564. errorCallback();
  65565. }
  65566. }
  65567. });
  65568. };
  65569. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  65570. if (this.isSupported && this.db) {
  65571. var targetStore;
  65572. if (url.indexOf(".babylon") !== -1) {
  65573. targetStore = "scenes";
  65574. }
  65575. else {
  65576. targetStore = "textures";
  65577. }
  65578. var file;
  65579. var transaction = this.db.transaction([targetStore]);
  65580. transaction.oncomplete = function (event) {
  65581. if (file) {
  65582. callback(file.data);
  65583. }
  65584. else {
  65585. notInDBCallback();
  65586. }
  65587. };
  65588. transaction.onabort = function (event) {
  65589. notInDBCallback();
  65590. };
  65591. var getRequest = transaction.objectStore(targetStore).get(url);
  65592. getRequest.onsuccess = function (event) {
  65593. file = (event.target).result;
  65594. };
  65595. getRequest.onerror = function (event) {
  65596. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  65597. notInDBCallback();
  65598. };
  65599. }
  65600. else {
  65601. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65602. callback();
  65603. }
  65604. };
  65605. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  65606. var _this = this;
  65607. if (this.isSupported) {
  65608. var targetStore;
  65609. if (url.indexOf(".babylon") !== -1) {
  65610. targetStore = "scenes";
  65611. }
  65612. else {
  65613. targetStore = "textures";
  65614. }
  65615. // Create XHR
  65616. var xhr = new XMLHttpRequest();
  65617. var fileData;
  65618. xhr.open("GET", url, true);
  65619. if (useArrayBuffer) {
  65620. xhr.responseType = "arraybuffer";
  65621. }
  65622. if (progressCallback) {
  65623. xhr.onprogress = progressCallback;
  65624. }
  65625. xhr.addEventListener("load", function () {
  65626. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  65627. // Blob as response (XHR2)
  65628. //fileData = xhr.responseText;
  65629. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  65630. if (!_this.hasReachedQuota && _this.db) {
  65631. // Open a transaction to the database
  65632. var transaction = _this.db.transaction([targetStore], "readwrite");
  65633. // the transaction could abort because of a QuotaExceededError error
  65634. transaction.onabort = function (event) {
  65635. try {
  65636. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  65637. var error = event.srcElement['error'];
  65638. if (error && error.name === "QuotaExceededError") {
  65639. _this.hasReachedQuota = true;
  65640. }
  65641. }
  65642. catch (ex) { }
  65643. callback(fileData);
  65644. };
  65645. transaction.oncomplete = function (event) {
  65646. callback(fileData);
  65647. };
  65648. var newFile;
  65649. if (targetStore === "scenes") {
  65650. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  65651. }
  65652. else {
  65653. newFile = { textureUrl: url, data: fileData };
  65654. }
  65655. try {
  65656. // Put the scene into the database
  65657. var addRequest = transaction.objectStore(targetStore).put(newFile);
  65658. addRequest.onsuccess = function (event) {
  65659. };
  65660. addRequest.onerror = function (event) {
  65661. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  65662. };
  65663. }
  65664. catch (ex) {
  65665. callback(fileData);
  65666. }
  65667. }
  65668. else {
  65669. callback(fileData);
  65670. }
  65671. }
  65672. else {
  65673. callback();
  65674. }
  65675. }, false);
  65676. xhr.addEventListener("error", function (event) {
  65677. BABYLON.Tools.Error("error on XHR request.");
  65678. callback();
  65679. }, false);
  65680. xhr.send();
  65681. }
  65682. else {
  65683. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  65684. callback();
  65685. }
  65686. };
  65687. Database.IsUASupportingBlobStorage = true;
  65688. Database.IDBStorageEnabled = true;
  65689. Database.parseURL = function (url) {
  65690. var a = document.createElement('a');
  65691. a.href = url;
  65692. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  65693. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  65694. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  65695. return absLocation;
  65696. };
  65697. Database.ReturnFullUrlLocation = function (url) {
  65698. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  65699. return (Database.parseURL(window.location.href) + url);
  65700. }
  65701. else {
  65702. return url;
  65703. }
  65704. };
  65705. return Database;
  65706. }());
  65707. BABYLON.Database = Database;
  65708. })(BABYLON || (BABYLON = {}));
  65709. //# sourceMappingURL=babylon.database.js.map
  65710. "use strict";
  65711. var BABYLON;
  65712. (function (BABYLON) {
  65713. var FresnelParameters = /** @class */ (function () {
  65714. function FresnelParameters() {
  65715. this._isEnabled = true;
  65716. this.leftColor = BABYLON.Color3.White();
  65717. this.rightColor = BABYLON.Color3.Black();
  65718. this.bias = 0;
  65719. this.power = 1;
  65720. }
  65721. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  65722. get: function () {
  65723. return this._isEnabled;
  65724. },
  65725. set: function (value) {
  65726. if (this._isEnabled === value) {
  65727. return;
  65728. }
  65729. this._isEnabled = value;
  65730. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  65731. },
  65732. enumerable: true,
  65733. configurable: true
  65734. });
  65735. FresnelParameters.prototype.clone = function () {
  65736. var newFresnelParameters = new FresnelParameters();
  65737. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  65738. return newFresnelParameters;
  65739. };
  65740. FresnelParameters.prototype.serialize = function () {
  65741. var serializationObject = {};
  65742. serializationObject.isEnabled = this.isEnabled;
  65743. serializationObject.leftColor = this.leftColor.asArray();
  65744. serializationObject.rightColor = this.rightColor.asArray();
  65745. serializationObject.bias = this.bias;
  65746. serializationObject.power = this.power;
  65747. return serializationObject;
  65748. };
  65749. FresnelParameters.Parse = function (parsedFresnelParameters) {
  65750. var fresnelParameters = new FresnelParameters();
  65751. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  65752. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  65753. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  65754. fresnelParameters.bias = parsedFresnelParameters.bias;
  65755. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  65756. return fresnelParameters;
  65757. };
  65758. return FresnelParameters;
  65759. }());
  65760. BABYLON.FresnelParameters = FresnelParameters;
  65761. })(BABYLON || (BABYLON = {}));
  65762. //# sourceMappingURL=babylon.fresnelParameters.js.map
  65763. "use strict";
  65764. var BABYLON;
  65765. (function (BABYLON) {
  65766. var MultiMaterial = /** @class */ (function (_super) {
  65767. __extends(MultiMaterial, _super);
  65768. function MultiMaterial(name, scene) {
  65769. var _this = _super.call(this, name, scene, true) || this;
  65770. scene.multiMaterials.push(_this);
  65771. _this.subMaterials = new Array();
  65772. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  65773. return _this;
  65774. }
  65775. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65776. get: function () {
  65777. return this._subMaterials;
  65778. },
  65779. set: function (value) {
  65780. this._subMaterials = value;
  65781. this._hookArray(value);
  65782. },
  65783. enumerable: true,
  65784. configurable: true
  65785. });
  65786. MultiMaterial.prototype._hookArray = function (array) {
  65787. var _this = this;
  65788. var oldPush = array.push;
  65789. array.push = function () {
  65790. var items = [];
  65791. for (var _i = 0; _i < arguments.length; _i++) {
  65792. items[_i] = arguments[_i];
  65793. }
  65794. var result = oldPush.apply(array, items);
  65795. _this._markAllSubMeshesAsTexturesDirty();
  65796. return result;
  65797. };
  65798. var oldSplice = array.splice;
  65799. array.splice = function (index, deleteCount) {
  65800. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65801. _this._markAllSubMeshesAsTexturesDirty();
  65802. return deleted;
  65803. };
  65804. };
  65805. // Properties
  65806. MultiMaterial.prototype.getSubMaterial = function (index) {
  65807. if (index < 0 || index >= this.subMaterials.length) {
  65808. return this.getScene().defaultMaterial;
  65809. }
  65810. return this.subMaterials[index];
  65811. };
  65812. MultiMaterial.prototype.getActiveTextures = function () {
  65813. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65814. if (subMaterial) {
  65815. return subMaterial.getActiveTextures();
  65816. }
  65817. else {
  65818. return [];
  65819. }
  65820. }));
  65821. var _a;
  65822. };
  65823. // Methods
  65824. MultiMaterial.prototype.getClassName = function () {
  65825. return "MultiMaterial";
  65826. };
  65827. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65828. for (var index = 0; index < this.subMaterials.length; index++) {
  65829. var subMaterial = this.subMaterials[index];
  65830. if (subMaterial) {
  65831. if (subMaterial.storeEffectOnSubMeshes) {
  65832. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65833. return false;
  65834. }
  65835. continue;
  65836. }
  65837. if (!subMaterial.isReady(mesh)) {
  65838. return false;
  65839. }
  65840. }
  65841. }
  65842. return true;
  65843. };
  65844. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65845. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65846. for (var index = 0; index < this.subMaterials.length; index++) {
  65847. var subMaterial = null;
  65848. var current = this.subMaterials[index];
  65849. if (cloneChildren && current) {
  65850. subMaterial = current.clone(name + "-" + current.name);
  65851. }
  65852. else {
  65853. subMaterial = this.subMaterials[index];
  65854. }
  65855. newMultiMaterial.subMaterials.push(subMaterial);
  65856. }
  65857. return newMultiMaterial;
  65858. };
  65859. MultiMaterial.prototype.serialize = function () {
  65860. var serializationObject = {};
  65861. serializationObject.name = this.name;
  65862. serializationObject.id = this.id;
  65863. if (BABYLON.Tags) {
  65864. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65865. }
  65866. serializationObject.materials = [];
  65867. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65868. var subMat = this.subMaterials[matIndex];
  65869. if (subMat) {
  65870. serializationObject.materials.push(subMat.id);
  65871. }
  65872. else {
  65873. serializationObject.materials.push(null);
  65874. }
  65875. }
  65876. return serializationObject;
  65877. };
  65878. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65879. var scene = this.getScene();
  65880. if (!scene) {
  65881. return;
  65882. }
  65883. var index = scene.multiMaterials.indexOf(this);
  65884. if (index >= 0) {
  65885. scene.multiMaterials.splice(index, 1);
  65886. }
  65887. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65888. };
  65889. return MultiMaterial;
  65890. }(BABYLON.Material));
  65891. BABYLON.MultiMaterial = MultiMaterial;
  65892. })(BABYLON || (BABYLON = {}));
  65893. //# sourceMappingURL=babylon.multiMaterial.js.map
  65894. "use strict";
  65895. var BABYLON;
  65896. (function (BABYLON) {
  65897. var FreeCameraTouchInput = /** @class */ (function () {
  65898. function FreeCameraTouchInput() {
  65899. this._offsetX = null;
  65900. this._offsetY = null;
  65901. this._pointerPressed = new Array();
  65902. this.touchAngularSensibility = 200000.0;
  65903. this.touchMoveSensibility = 250.0;
  65904. }
  65905. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65906. var _this = this;
  65907. var previousPosition = null;
  65908. if (this._pointerInput === undefined) {
  65909. this._onLostFocus = function (evt) {
  65910. _this._offsetX = null;
  65911. _this._offsetY = null;
  65912. };
  65913. this._pointerInput = function (p, s) {
  65914. var evt = p.event;
  65915. if (evt.pointerType === "mouse") {
  65916. return;
  65917. }
  65918. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65919. if (!noPreventDefault) {
  65920. evt.preventDefault();
  65921. }
  65922. _this._pointerPressed.push(evt.pointerId);
  65923. if (_this._pointerPressed.length !== 1) {
  65924. return;
  65925. }
  65926. previousPosition = {
  65927. x: evt.clientX,
  65928. y: evt.clientY
  65929. };
  65930. }
  65931. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65932. if (!noPreventDefault) {
  65933. evt.preventDefault();
  65934. }
  65935. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65936. if (index === -1) {
  65937. return;
  65938. }
  65939. _this._pointerPressed.splice(index, 1);
  65940. if (index != 0) {
  65941. return;
  65942. }
  65943. previousPosition = null;
  65944. _this._offsetX = null;
  65945. _this._offsetY = null;
  65946. }
  65947. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65948. if (!noPreventDefault) {
  65949. evt.preventDefault();
  65950. }
  65951. if (!previousPosition) {
  65952. return;
  65953. }
  65954. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65955. if (index != 0) {
  65956. return;
  65957. }
  65958. _this._offsetX = evt.clientX - previousPosition.x;
  65959. _this._offsetY = -(evt.clientY - previousPosition.y);
  65960. }
  65961. };
  65962. }
  65963. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65964. if (this._onLostFocus) {
  65965. element.addEventListener("blur", this._onLostFocus);
  65966. }
  65967. };
  65968. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65969. if (this._pointerInput && element) {
  65970. if (this._observer) {
  65971. this.camera.getScene().onPointerObservable.remove(this._observer);
  65972. this._observer = null;
  65973. }
  65974. if (this._onLostFocus) {
  65975. element.removeEventListener("blur", this._onLostFocus);
  65976. this._onLostFocus = null;
  65977. }
  65978. this._pointerPressed = [];
  65979. this._offsetX = null;
  65980. this._offsetY = null;
  65981. }
  65982. };
  65983. FreeCameraTouchInput.prototype.checkInputs = function () {
  65984. if (this._offsetX && this._offsetY) {
  65985. var camera = this.camera;
  65986. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65987. if (this._pointerPressed.length > 1) {
  65988. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65989. }
  65990. else {
  65991. var speed = camera._computeLocalCameraSpeed();
  65992. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65993. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65994. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65995. }
  65996. }
  65997. };
  65998. FreeCameraTouchInput.prototype.getClassName = function () {
  65999. return "FreeCameraTouchInput";
  66000. };
  66001. FreeCameraTouchInput.prototype.getSimpleName = function () {
  66002. return "touch";
  66003. };
  66004. __decorate([
  66005. BABYLON.serialize()
  66006. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  66007. __decorate([
  66008. BABYLON.serialize()
  66009. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  66010. return FreeCameraTouchInput;
  66011. }());
  66012. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  66013. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  66014. })(BABYLON || (BABYLON = {}));
  66015. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  66016. "use strict";
  66017. var BABYLON;
  66018. (function (BABYLON) {
  66019. // We're mainly based on the logic defined into the FreeCamera code
  66020. var TouchCamera = /** @class */ (function (_super) {
  66021. __extends(TouchCamera, _super);
  66022. //-- end properties for backward compatibility for inputs
  66023. function TouchCamera(name, position, scene) {
  66024. var _this = _super.call(this, name, position, scene) || this;
  66025. _this.inputs.addTouch();
  66026. _this._setupInputs();
  66027. return _this;
  66028. }
  66029. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  66030. //-- Begin properties for backward compatibility for inputs
  66031. get: function () {
  66032. var touch = this.inputs.attached["touch"];
  66033. if (touch)
  66034. return touch.touchAngularSensibility;
  66035. return 0;
  66036. },
  66037. set: function (value) {
  66038. var touch = this.inputs.attached["touch"];
  66039. if (touch)
  66040. touch.touchAngularSensibility = value;
  66041. },
  66042. enumerable: true,
  66043. configurable: true
  66044. });
  66045. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  66046. get: function () {
  66047. var touch = this.inputs.attached["touch"];
  66048. if (touch)
  66049. return touch.touchMoveSensibility;
  66050. return 0;
  66051. },
  66052. set: function (value) {
  66053. var touch = this.inputs.attached["touch"];
  66054. if (touch)
  66055. touch.touchMoveSensibility = value;
  66056. },
  66057. enumerable: true,
  66058. configurable: true
  66059. });
  66060. TouchCamera.prototype.getClassName = function () {
  66061. return "TouchCamera";
  66062. };
  66063. TouchCamera.prototype._setupInputs = function () {
  66064. var mouse = this.inputs.attached["mouse"];
  66065. if (mouse) {
  66066. mouse.touchEnabled = false;
  66067. }
  66068. };
  66069. return TouchCamera;
  66070. }(BABYLON.FreeCamera));
  66071. BABYLON.TouchCamera = TouchCamera;
  66072. })(BABYLON || (BABYLON = {}));
  66073. //# sourceMappingURL=babylon.touchCamera.js.map
  66074. "use strict";
  66075. var BABYLON;
  66076. (function (BABYLON) {
  66077. var ProceduralTexture = /** @class */ (function (_super) {
  66078. __extends(ProceduralTexture, _super);
  66079. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  66080. if (fallbackTexture === void 0) { fallbackTexture = null; }
  66081. if (generateMipMaps === void 0) { generateMipMaps = true; }
  66082. if (isCube === void 0) { isCube = false; }
  66083. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66084. _this.isCube = isCube;
  66085. _this.isEnabled = true;
  66086. _this._currentRefreshId = -1;
  66087. _this._refreshRate = 1;
  66088. _this._vertexBuffers = {};
  66089. _this._uniforms = new Array();
  66090. _this._samplers = new Array();
  66091. _this._textures = {};
  66092. _this._floats = {};
  66093. _this._floatsArrays = {};
  66094. _this._colors3 = {};
  66095. _this._colors4 = {};
  66096. _this._vectors2 = {};
  66097. _this._vectors3 = {};
  66098. _this._matrices = {};
  66099. _this._fallbackTextureUsed = false;
  66100. scene.proceduralTextures.push(_this);
  66101. _this._engine = scene.getEngine();
  66102. _this.name = name;
  66103. _this.isRenderTarget = true;
  66104. _this._size = size;
  66105. _this._generateMipMaps = generateMipMaps;
  66106. _this.setFragment(fragment);
  66107. _this._fallbackTexture = fallbackTexture;
  66108. if (isCube) {
  66109. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  66110. _this.setFloat("face", 0);
  66111. }
  66112. else {
  66113. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  66114. }
  66115. // VBO
  66116. var vertices = [];
  66117. vertices.push(1, 1);
  66118. vertices.push(-1, 1);
  66119. vertices.push(-1, -1);
  66120. vertices.push(1, -1);
  66121. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66122. _this._createIndexBuffer();
  66123. return _this;
  66124. }
  66125. ProceduralTexture.prototype._createIndexBuffer = function () {
  66126. var engine = this._engine;
  66127. // Indices
  66128. var indices = [];
  66129. indices.push(0);
  66130. indices.push(1);
  66131. indices.push(2);
  66132. indices.push(0);
  66133. indices.push(2);
  66134. indices.push(3);
  66135. this._indexBuffer = engine.createIndexBuffer(indices);
  66136. };
  66137. ProceduralTexture.prototype._rebuild = function () {
  66138. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66139. if (vb) {
  66140. vb._rebuild();
  66141. }
  66142. this._createIndexBuffer();
  66143. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66144. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66145. }
  66146. };
  66147. ProceduralTexture.prototype.reset = function () {
  66148. if (this._effect === undefined) {
  66149. return;
  66150. }
  66151. var engine = this._engine;
  66152. engine._releaseEffect(this._effect);
  66153. };
  66154. ProceduralTexture.prototype.isReady = function () {
  66155. var _this = this;
  66156. var engine = this._engine;
  66157. var shaders;
  66158. if (!this._fragment) {
  66159. return false;
  66160. }
  66161. if (this._fallbackTextureUsed) {
  66162. return true;
  66163. }
  66164. if (this._fragment.fragmentElement !== undefined) {
  66165. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  66166. }
  66167. else {
  66168. shaders = { vertex: "procedural", fragment: this._fragment };
  66169. }
  66170. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  66171. _this.releaseInternalTexture();
  66172. if (_this._fallbackTexture) {
  66173. _this._texture = _this._fallbackTexture._texture;
  66174. if (_this._texture) {
  66175. _this._texture.incrementReferences();
  66176. }
  66177. }
  66178. _this._fallbackTextureUsed = true;
  66179. });
  66180. return this._effect.isReady();
  66181. };
  66182. ProceduralTexture.prototype.resetRefreshCounter = function () {
  66183. this._currentRefreshId = -1;
  66184. };
  66185. ProceduralTexture.prototype.setFragment = function (fragment) {
  66186. this._fragment = fragment;
  66187. };
  66188. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  66189. get: function () {
  66190. return this._refreshRate;
  66191. },
  66192. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66193. set: function (value) {
  66194. this._refreshRate = value;
  66195. this.resetRefreshCounter();
  66196. },
  66197. enumerable: true,
  66198. configurable: true
  66199. });
  66200. ProceduralTexture.prototype._shouldRender = function () {
  66201. if (!this.isEnabled || !this.isReady() || !this._texture) {
  66202. return false;
  66203. }
  66204. if (this._fallbackTextureUsed) {
  66205. return false;
  66206. }
  66207. if (this._currentRefreshId === -1) {
  66208. this._currentRefreshId = 1;
  66209. return true;
  66210. }
  66211. if (this.refreshRate === this._currentRefreshId) {
  66212. this._currentRefreshId = 1;
  66213. return true;
  66214. }
  66215. this._currentRefreshId++;
  66216. return false;
  66217. };
  66218. ProceduralTexture.prototype.getRenderSize = function () {
  66219. return this._size;
  66220. };
  66221. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  66222. if (this._fallbackTextureUsed) {
  66223. return;
  66224. }
  66225. this.releaseInternalTexture();
  66226. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  66227. };
  66228. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  66229. if (this._uniforms.indexOf(uniformName) === -1) {
  66230. this._uniforms.push(uniformName);
  66231. }
  66232. };
  66233. ProceduralTexture.prototype.setTexture = function (name, texture) {
  66234. if (this._samplers.indexOf(name) === -1) {
  66235. this._samplers.push(name);
  66236. }
  66237. this._textures[name] = texture;
  66238. return this;
  66239. };
  66240. ProceduralTexture.prototype.setFloat = function (name, value) {
  66241. this._checkUniform(name);
  66242. this._floats[name] = value;
  66243. return this;
  66244. };
  66245. ProceduralTexture.prototype.setFloats = function (name, value) {
  66246. this._checkUniform(name);
  66247. this._floatsArrays[name] = value;
  66248. return this;
  66249. };
  66250. ProceduralTexture.prototype.setColor3 = function (name, value) {
  66251. this._checkUniform(name);
  66252. this._colors3[name] = value;
  66253. return this;
  66254. };
  66255. ProceduralTexture.prototype.setColor4 = function (name, value) {
  66256. this._checkUniform(name);
  66257. this._colors4[name] = value;
  66258. return this;
  66259. };
  66260. ProceduralTexture.prototype.setVector2 = function (name, value) {
  66261. this._checkUniform(name);
  66262. this._vectors2[name] = value;
  66263. return this;
  66264. };
  66265. ProceduralTexture.prototype.setVector3 = function (name, value) {
  66266. this._checkUniform(name);
  66267. this._vectors3[name] = value;
  66268. return this;
  66269. };
  66270. ProceduralTexture.prototype.setMatrix = function (name, value) {
  66271. this._checkUniform(name);
  66272. this._matrices[name] = value;
  66273. return this;
  66274. };
  66275. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  66276. var scene = this.getScene();
  66277. if (!scene) {
  66278. return;
  66279. }
  66280. var engine = this._engine;
  66281. // Render
  66282. engine.enableEffect(this._effect);
  66283. engine.setState(false);
  66284. // Texture
  66285. for (var name in this._textures) {
  66286. this._effect.setTexture(name, this._textures[name]);
  66287. }
  66288. // Float
  66289. for (name in this._floats) {
  66290. this._effect.setFloat(name, this._floats[name]);
  66291. }
  66292. // Floats
  66293. for (name in this._floatsArrays) {
  66294. this._effect.setArray(name, this._floatsArrays[name]);
  66295. }
  66296. // Color3
  66297. for (name in this._colors3) {
  66298. this._effect.setColor3(name, this._colors3[name]);
  66299. }
  66300. // Color4
  66301. for (name in this._colors4) {
  66302. var color = this._colors4[name];
  66303. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  66304. }
  66305. // Vector2
  66306. for (name in this._vectors2) {
  66307. this._effect.setVector2(name, this._vectors2[name]);
  66308. }
  66309. // Vector3
  66310. for (name in this._vectors3) {
  66311. this._effect.setVector3(name, this._vectors3[name]);
  66312. }
  66313. // Matrix
  66314. for (name in this._matrices) {
  66315. this._effect.setMatrix(name, this._matrices[name]);
  66316. }
  66317. if (!this._texture) {
  66318. return;
  66319. }
  66320. if (this.isCube) {
  66321. for (var face = 0; face < 6; face++) {
  66322. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  66323. // VBOs
  66324. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66325. this._effect.setFloat("face", face);
  66326. // Clear
  66327. engine.clear(scene.clearColor, true, true, true);
  66328. // Draw order
  66329. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66330. // Mipmaps
  66331. if (face === 5) {
  66332. engine.generateMipMapsForCubemap(this._texture);
  66333. }
  66334. }
  66335. }
  66336. else {
  66337. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  66338. // VBOs
  66339. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66340. // Clear
  66341. engine.clear(scene.clearColor, true, true, true);
  66342. // Draw order
  66343. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  66344. }
  66345. // Unbind
  66346. engine.unBindFramebuffer(this._texture, this.isCube);
  66347. if (this.onGenerated) {
  66348. this.onGenerated();
  66349. }
  66350. };
  66351. ProceduralTexture.prototype.clone = function () {
  66352. var textureSize = this.getSize();
  66353. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  66354. // Base texture
  66355. newTexture.hasAlpha = this.hasAlpha;
  66356. newTexture.level = this.level;
  66357. // RenderTarget Texture
  66358. newTexture.coordinatesMode = this.coordinatesMode;
  66359. return newTexture;
  66360. };
  66361. ProceduralTexture.prototype.dispose = function () {
  66362. var scene = this.getScene();
  66363. if (!scene) {
  66364. return;
  66365. }
  66366. var index = scene.proceduralTextures.indexOf(this);
  66367. if (index >= 0) {
  66368. scene.proceduralTextures.splice(index, 1);
  66369. }
  66370. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  66371. if (vertexBuffer) {
  66372. vertexBuffer.dispose();
  66373. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  66374. }
  66375. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  66376. this._indexBuffer = null;
  66377. }
  66378. _super.prototype.dispose.call(this);
  66379. };
  66380. return ProceduralTexture;
  66381. }(BABYLON.Texture));
  66382. BABYLON.ProceduralTexture = ProceduralTexture;
  66383. })(BABYLON || (BABYLON = {}));
  66384. //# sourceMappingURL=babylon.proceduralTexture.js.map
  66385. "use strict";
  66386. var BABYLON;
  66387. (function (BABYLON) {
  66388. var CustomProceduralTexture = /** @class */ (function (_super) {
  66389. __extends(CustomProceduralTexture, _super);
  66390. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  66391. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  66392. _this._animate = true;
  66393. _this._time = 0;
  66394. _this._texturePath = texturePath;
  66395. //Try to load json
  66396. _this.loadJson(texturePath);
  66397. _this.refreshRate = 1;
  66398. return _this;
  66399. }
  66400. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  66401. var _this = this;
  66402. var noConfigFile = function () {
  66403. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  66404. try {
  66405. _this.setFragment(_this._texturePath);
  66406. }
  66407. catch (ex) {
  66408. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  66409. }
  66410. };
  66411. var configFileUrl = jsonUrl + "/config.json";
  66412. var xhr = new XMLHttpRequest();
  66413. xhr.open("GET", configFileUrl, true);
  66414. xhr.addEventListener("load", function () {
  66415. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  66416. try {
  66417. _this._config = JSON.parse(xhr.response);
  66418. _this.updateShaderUniforms();
  66419. _this.updateTextures();
  66420. _this.setFragment(_this._texturePath + "/custom");
  66421. _this._animate = _this._config.animate;
  66422. _this.refreshRate = _this._config.refreshrate;
  66423. }
  66424. catch (ex) {
  66425. noConfigFile();
  66426. }
  66427. }
  66428. else {
  66429. noConfigFile();
  66430. }
  66431. }, false);
  66432. xhr.addEventListener("error", function () {
  66433. noConfigFile();
  66434. }, false);
  66435. try {
  66436. xhr.send();
  66437. }
  66438. catch (ex) {
  66439. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  66440. }
  66441. };
  66442. CustomProceduralTexture.prototype.isReady = function () {
  66443. if (!_super.prototype.isReady.call(this)) {
  66444. return false;
  66445. }
  66446. for (var name in this._textures) {
  66447. var texture = this._textures[name];
  66448. if (!texture.isReady()) {
  66449. return false;
  66450. }
  66451. }
  66452. return true;
  66453. };
  66454. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  66455. var scene = this.getScene();
  66456. if (this._animate && scene) {
  66457. this._time += scene.getAnimationRatio() * 0.03;
  66458. this.updateShaderUniforms();
  66459. }
  66460. _super.prototype.render.call(this, useCameraPostProcess);
  66461. };
  66462. CustomProceduralTexture.prototype.updateTextures = function () {
  66463. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  66464. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  66465. }
  66466. };
  66467. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  66468. if (this._config) {
  66469. for (var j = 0; j < this._config.uniforms.length; j++) {
  66470. var uniform = this._config.uniforms[j];
  66471. switch (uniform.type) {
  66472. case "float":
  66473. this.setFloat(uniform.name, uniform.value);
  66474. break;
  66475. case "color3":
  66476. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  66477. break;
  66478. case "color4":
  66479. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  66480. break;
  66481. case "vector2":
  66482. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  66483. break;
  66484. case "vector3":
  66485. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  66486. break;
  66487. }
  66488. }
  66489. }
  66490. this.setFloat("time", this._time);
  66491. };
  66492. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  66493. get: function () {
  66494. return this._animate;
  66495. },
  66496. set: function (value) {
  66497. this._animate = value;
  66498. },
  66499. enumerable: true,
  66500. configurable: true
  66501. });
  66502. return CustomProceduralTexture;
  66503. }(BABYLON.ProceduralTexture));
  66504. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  66505. })(BABYLON || (BABYLON = {}));
  66506. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  66507. "use strict";
  66508. var BABYLON;
  66509. (function (BABYLON) {
  66510. var FreeCameraGamepadInput = /** @class */ (function () {
  66511. function FreeCameraGamepadInput() {
  66512. this.gamepadAngularSensibility = 200;
  66513. this.gamepadMoveSensibility = 40;
  66514. // private members
  66515. this._cameraTransform = BABYLON.Matrix.Identity();
  66516. this._deltaTransform = BABYLON.Vector3.Zero();
  66517. this._vector3 = BABYLON.Vector3.Zero();
  66518. this._vector2 = BABYLON.Vector2.Zero();
  66519. }
  66520. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  66521. var _this = this;
  66522. var manager = this.camera.getScene().gamepadManager;
  66523. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66524. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  66525. // prioritize XBOX gamepads.
  66526. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  66527. _this.gamepad = gamepad;
  66528. }
  66529. }
  66530. });
  66531. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66532. if (_this.gamepad === gamepad) {
  66533. _this.gamepad = null;
  66534. }
  66535. });
  66536. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  66537. };
  66538. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  66539. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66540. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66541. this.gamepad = null;
  66542. };
  66543. FreeCameraGamepadInput.prototype.checkInputs = function () {
  66544. if (this.gamepad && this.gamepad.leftStick) {
  66545. var camera = this.camera;
  66546. var LSValues = this.gamepad.leftStick;
  66547. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  66548. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  66549. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  66550. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  66551. var RSValues = this.gamepad.rightStick;
  66552. if (RSValues) {
  66553. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  66554. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  66555. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  66556. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  66557. }
  66558. else {
  66559. RSValues = { x: 0, y: 0 };
  66560. }
  66561. if (!camera.rotationQuaternion) {
  66562. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  66563. }
  66564. else {
  66565. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  66566. }
  66567. var speed = camera._computeLocalCameraSpeed() * 50.0;
  66568. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  66569. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  66570. camera.cameraDirection.addInPlace(this._deltaTransform);
  66571. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  66572. camera.cameraRotation.addInPlace(this._vector2);
  66573. }
  66574. };
  66575. FreeCameraGamepadInput.prototype.getClassName = function () {
  66576. return "FreeCameraGamepadInput";
  66577. };
  66578. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  66579. return "gamepad";
  66580. };
  66581. __decorate([
  66582. BABYLON.serialize()
  66583. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  66584. __decorate([
  66585. BABYLON.serialize()
  66586. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  66587. return FreeCameraGamepadInput;
  66588. }());
  66589. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  66590. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  66591. })(BABYLON || (BABYLON = {}));
  66592. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  66593. "use strict";
  66594. var BABYLON;
  66595. (function (BABYLON) {
  66596. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  66597. function ArcRotateCameraGamepadInput() {
  66598. this.gamepadRotationSensibility = 80;
  66599. this.gamepadMoveSensibility = 40;
  66600. }
  66601. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  66602. var _this = this;
  66603. var manager = this.camera.getScene().gamepadManager;
  66604. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  66605. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  66606. // prioritize XBOX gamepads.
  66607. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  66608. _this.gamepad = gamepad;
  66609. }
  66610. }
  66611. });
  66612. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  66613. if (_this.gamepad === gamepad) {
  66614. _this.gamepad = null;
  66615. }
  66616. });
  66617. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  66618. };
  66619. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  66620. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  66621. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  66622. this.gamepad = null;
  66623. };
  66624. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  66625. if (this.gamepad) {
  66626. var camera = this.camera;
  66627. var RSValues = this.gamepad.rightStick;
  66628. if (RSValues) {
  66629. if (RSValues.x != 0) {
  66630. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  66631. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  66632. camera.inertialAlphaOffset += normalizedRX;
  66633. }
  66634. }
  66635. if (RSValues.y != 0) {
  66636. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  66637. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  66638. camera.inertialBetaOffset += normalizedRY;
  66639. }
  66640. }
  66641. }
  66642. var LSValues = this.gamepad.leftStick;
  66643. if (LSValues && LSValues.y != 0) {
  66644. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  66645. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  66646. this.camera.inertialRadiusOffset -= normalizedLY;
  66647. }
  66648. }
  66649. }
  66650. };
  66651. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  66652. return "ArcRotateCameraGamepadInput";
  66653. };
  66654. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  66655. return "gamepad";
  66656. };
  66657. __decorate([
  66658. BABYLON.serialize()
  66659. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  66660. __decorate([
  66661. BABYLON.serialize()
  66662. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  66663. return ArcRotateCameraGamepadInput;
  66664. }());
  66665. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  66666. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  66667. })(BABYLON || (BABYLON = {}));
  66668. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  66669. "use strict";
  66670. var BABYLON;
  66671. (function (BABYLON) {
  66672. var GamepadManager = /** @class */ (function () {
  66673. function GamepadManager(_scene) {
  66674. var _this = this;
  66675. this._scene = _scene;
  66676. this._babylonGamepads = [];
  66677. this._oneGamepadConnected = false;
  66678. this._isMonitoring = false;
  66679. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  66680. if (!BABYLON.Tools.IsWindowObjectExist()) {
  66681. this._gamepadEventSupported = false;
  66682. }
  66683. else {
  66684. this._gamepadEventSupported = 'GamepadEvent' in window;
  66685. this._gamepadSupport = (navigator.getGamepads ||
  66686. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  66687. }
  66688. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  66689. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  66690. for (var i in _this._babylonGamepads) {
  66691. var gamepad = _this._babylonGamepads[i];
  66692. if (gamepad && gamepad._isConnected) {
  66693. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  66694. }
  66695. }
  66696. });
  66697. this._onGamepadConnectedEvent = function (evt) {
  66698. var gamepad = evt.gamepad;
  66699. if (gamepad.index in _this._babylonGamepads) {
  66700. if (_this._babylonGamepads[gamepad.index].isConnected) {
  66701. return;
  66702. }
  66703. }
  66704. var newGamepad;
  66705. if (_this._babylonGamepads[gamepad.index]) {
  66706. newGamepad = _this._babylonGamepads[gamepad.index];
  66707. newGamepad.browserGamepad = gamepad;
  66708. newGamepad._isConnected = true;
  66709. }
  66710. else {
  66711. newGamepad = _this._addNewGamepad(gamepad);
  66712. }
  66713. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66714. _this._startMonitoringGamepads();
  66715. };
  66716. this._onGamepadDisconnectedEvent = function (evt) {
  66717. var gamepad = evt.gamepad;
  66718. // Remove the gamepad from the list of gamepads to monitor.
  66719. for (var i in _this._babylonGamepads) {
  66720. if (_this._babylonGamepads[i].index === gamepad.index) {
  66721. var disconnectedGamepad = _this._babylonGamepads[i];
  66722. disconnectedGamepad._isConnected = false;
  66723. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  66724. break;
  66725. }
  66726. }
  66727. };
  66728. if (this._gamepadSupport) {
  66729. //first add already-connected gamepads
  66730. this._updateGamepadObjects();
  66731. if (this._babylonGamepads.length) {
  66732. this._startMonitoringGamepads();
  66733. }
  66734. // Checking if the gamepad connected event is supported (like in Firefox)
  66735. if (this._gamepadEventSupported) {
  66736. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  66737. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  66738. }
  66739. else {
  66740. this._startMonitoringGamepads();
  66741. }
  66742. }
  66743. }
  66744. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  66745. get: function () {
  66746. return this._babylonGamepads;
  66747. },
  66748. enumerable: true,
  66749. configurable: true
  66750. });
  66751. GamepadManager.prototype.getGamepadByType = function (type) {
  66752. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  66753. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  66754. var gamepad = _a[_i];
  66755. if (gamepad && gamepad.type === type) {
  66756. return gamepad;
  66757. }
  66758. }
  66759. return null;
  66760. };
  66761. GamepadManager.prototype.dispose = function () {
  66762. if (this._gamepadEventSupported) {
  66763. if (this._onGamepadConnectedEvent) {
  66764. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  66765. }
  66766. if (this._onGamepadDisconnectedEvent) {
  66767. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  66768. }
  66769. this._onGamepadConnectedEvent = null;
  66770. this._onGamepadDisconnectedEvent = null;
  66771. }
  66772. this._babylonGamepads.forEach(function (gamepad) {
  66773. gamepad.dispose();
  66774. });
  66775. this.onGamepadConnectedObservable.clear();
  66776. this.onGamepadDisconnectedObservable.clear();
  66777. this._oneGamepadConnected = false;
  66778. this._stopMonitoringGamepads();
  66779. this._babylonGamepads = [];
  66780. };
  66781. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66782. if (!this._oneGamepadConnected) {
  66783. this._oneGamepadConnected = true;
  66784. }
  66785. var newGamepad;
  66786. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66787. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66788. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66789. }
  66790. else if (gamepad.pose) {
  66791. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66792. }
  66793. else {
  66794. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66795. }
  66796. this._babylonGamepads[newGamepad.index] = newGamepad;
  66797. return newGamepad;
  66798. };
  66799. GamepadManager.prototype._startMonitoringGamepads = function () {
  66800. if (!this._isMonitoring) {
  66801. this._isMonitoring = true;
  66802. //back-comp
  66803. if (!this._scene) {
  66804. this._checkGamepadsStatus();
  66805. }
  66806. }
  66807. };
  66808. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66809. this._isMonitoring = false;
  66810. };
  66811. GamepadManager.prototype._checkGamepadsStatus = function () {
  66812. var _this = this;
  66813. // Hack to be compatible Chrome
  66814. this._updateGamepadObjects();
  66815. for (var i in this._babylonGamepads) {
  66816. var gamepad = this._babylonGamepads[i];
  66817. if (!gamepad || !gamepad.isConnected) {
  66818. continue;
  66819. }
  66820. gamepad.update();
  66821. }
  66822. if (this._isMonitoring && !this._scene) {
  66823. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66824. }
  66825. };
  66826. // This function is called only on Chrome, which does not properly support
  66827. // connection/disconnection events and forces you to recopy again the gamepad object
  66828. GamepadManager.prototype._updateGamepadObjects = function () {
  66829. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66830. for (var i = 0; i < gamepads.length; i++) {
  66831. if (gamepads[i]) {
  66832. if (!this._babylonGamepads[gamepads[i].index]) {
  66833. var newGamepad = this._addNewGamepad(gamepads[i]);
  66834. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66835. }
  66836. else {
  66837. // Forced to copy again this object for Chrome for unknown reason
  66838. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66839. if (!this._babylonGamepads[i].isConnected) {
  66840. this._babylonGamepads[i]._isConnected = true;
  66841. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66842. }
  66843. }
  66844. }
  66845. }
  66846. };
  66847. return GamepadManager;
  66848. }());
  66849. BABYLON.GamepadManager = GamepadManager;
  66850. })(BABYLON || (BABYLON = {}));
  66851. //# sourceMappingURL=babylon.gamepadManager.js.map
  66852. "use strict";
  66853. var BABYLON;
  66854. (function (BABYLON) {
  66855. var StickValues = /** @class */ (function () {
  66856. function StickValues(x, y) {
  66857. this.x = x;
  66858. this.y = y;
  66859. }
  66860. return StickValues;
  66861. }());
  66862. BABYLON.StickValues = StickValues;
  66863. var Gamepad = /** @class */ (function () {
  66864. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66865. if (leftStickX === void 0) { leftStickX = 0; }
  66866. if (leftStickY === void 0) { leftStickY = 1; }
  66867. if (rightStickX === void 0) { rightStickX = 2; }
  66868. if (rightStickY === void 0) { rightStickY = 3; }
  66869. this.id = id;
  66870. this.index = index;
  66871. this.browserGamepad = browserGamepad;
  66872. this._isConnected = true;
  66873. this._invertLeftStickY = false;
  66874. this.type = Gamepad.GAMEPAD;
  66875. this._leftStickAxisX = leftStickX;
  66876. this._leftStickAxisY = leftStickY;
  66877. this._rightStickAxisX = rightStickX;
  66878. this._rightStickAxisY = rightStickY;
  66879. if (this.browserGamepad.axes.length >= 2) {
  66880. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66881. }
  66882. if (this.browserGamepad.axes.length >= 4) {
  66883. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66884. }
  66885. }
  66886. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66887. get: function () {
  66888. return this._isConnected;
  66889. },
  66890. enumerable: true,
  66891. configurable: true
  66892. });
  66893. Gamepad.prototype.onleftstickchanged = function (callback) {
  66894. this._onleftstickchanged = callback;
  66895. };
  66896. Gamepad.prototype.onrightstickchanged = function (callback) {
  66897. this._onrightstickchanged = callback;
  66898. };
  66899. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66900. get: function () {
  66901. return this._leftStick;
  66902. },
  66903. set: function (newValues) {
  66904. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66905. this._onleftstickchanged(newValues);
  66906. }
  66907. this._leftStick = newValues;
  66908. },
  66909. enumerable: true,
  66910. configurable: true
  66911. });
  66912. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66913. get: function () {
  66914. return this._rightStick;
  66915. },
  66916. set: function (newValues) {
  66917. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66918. this._onrightstickchanged(newValues);
  66919. }
  66920. this._rightStick = newValues;
  66921. },
  66922. enumerable: true,
  66923. configurable: true
  66924. });
  66925. Gamepad.prototype.update = function () {
  66926. if (this._leftStick) {
  66927. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66928. if (this._invertLeftStickY) {
  66929. this.leftStick.y *= -1;
  66930. }
  66931. }
  66932. if (this._rightStick) {
  66933. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66934. }
  66935. };
  66936. Gamepad.prototype.dispose = function () {
  66937. };
  66938. Gamepad.GAMEPAD = 0;
  66939. Gamepad.GENERIC = 1;
  66940. Gamepad.XBOX = 2;
  66941. Gamepad.POSE_ENABLED = 3;
  66942. return Gamepad;
  66943. }());
  66944. BABYLON.Gamepad = Gamepad;
  66945. var GenericPad = /** @class */ (function (_super) {
  66946. __extends(GenericPad, _super);
  66947. function GenericPad(id, index, browserGamepad) {
  66948. var _this = _super.call(this, id, index, browserGamepad) || this;
  66949. _this.onButtonDownObservable = new BABYLON.Observable();
  66950. _this.onButtonUpObservable = new BABYLON.Observable();
  66951. _this.type = Gamepad.GENERIC;
  66952. _this._buttons = new Array(browserGamepad.buttons.length);
  66953. return _this;
  66954. }
  66955. GenericPad.prototype.onbuttondown = function (callback) {
  66956. this._onbuttondown = callback;
  66957. };
  66958. GenericPad.prototype.onbuttonup = function (callback) {
  66959. this._onbuttonup = callback;
  66960. };
  66961. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66962. if (newValue !== currentValue) {
  66963. if (newValue === 1) {
  66964. if (this._onbuttondown) {
  66965. this._onbuttondown(buttonIndex);
  66966. }
  66967. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66968. }
  66969. if (newValue === 0) {
  66970. if (this._onbuttonup) {
  66971. this._onbuttonup(buttonIndex);
  66972. }
  66973. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66974. }
  66975. }
  66976. return newValue;
  66977. };
  66978. GenericPad.prototype.update = function () {
  66979. _super.prototype.update.call(this);
  66980. for (var index = 0; index < this._buttons.length; index++) {
  66981. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66982. }
  66983. };
  66984. GenericPad.prototype.dispose = function () {
  66985. _super.prototype.dispose.call(this);
  66986. this.onButtonDownObservable.clear();
  66987. this.onButtonUpObservable.clear();
  66988. };
  66989. return GenericPad;
  66990. }(Gamepad));
  66991. BABYLON.GenericPad = GenericPad;
  66992. })(BABYLON || (BABYLON = {}));
  66993. //# sourceMappingURL=babylon.gamepad.js.map
  66994. "use strict";
  66995. var BABYLON;
  66996. (function (BABYLON) {
  66997. var Xbox360Button;
  66998. (function (Xbox360Button) {
  66999. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  67000. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  67001. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  67002. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  67003. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  67004. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  67005. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  67006. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  67007. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  67008. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  67009. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  67010. var Xbox360Dpad;
  67011. (function (Xbox360Dpad) {
  67012. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  67013. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  67014. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  67015. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  67016. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  67017. var Xbox360Pad = /** @class */ (function (_super) {
  67018. __extends(Xbox360Pad, _super);
  67019. function Xbox360Pad(id, index, gamepad, xboxOne) {
  67020. if (xboxOne === void 0) { xboxOne = false; }
  67021. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  67022. _this._leftTrigger = 0;
  67023. _this._rightTrigger = 0;
  67024. _this.onButtonDownObservable = new BABYLON.Observable();
  67025. _this.onButtonUpObservable = new BABYLON.Observable();
  67026. _this.onPadDownObservable = new BABYLON.Observable();
  67027. _this.onPadUpObservable = new BABYLON.Observable();
  67028. _this._buttonA = 0;
  67029. _this._buttonB = 0;
  67030. _this._buttonX = 0;
  67031. _this._buttonY = 0;
  67032. _this._buttonBack = 0;
  67033. _this._buttonStart = 0;
  67034. _this._buttonLB = 0;
  67035. _this._buttonRB = 0;
  67036. _this._buttonLeftStick = 0;
  67037. _this._buttonRightStick = 0;
  67038. _this._dPadUp = 0;
  67039. _this._dPadDown = 0;
  67040. _this._dPadLeft = 0;
  67041. _this._dPadRight = 0;
  67042. _this._isXboxOnePad = false;
  67043. _this.type = BABYLON.Gamepad.XBOX;
  67044. _this._isXboxOnePad = xboxOne;
  67045. return _this;
  67046. }
  67047. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  67048. this._onlefttriggerchanged = callback;
  67049. };
  67050. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  67051. this._onrighttriggerchanged = callback;
  67052. };
  67053. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  67054. get: function () {
  67055. return this._leftTrigger;
  67056. },
  67057. set: function (newValue) {
  67058. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  67059. this._onlefttriggerchanged(newValue);
  67060. }
  67061. this._leftTrigger = newValue;
  67062. },
  67063. enumerable: true,
  67064. configurable: true
  67065. });
  67066. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  67067. get: function () {
  67068. return this._rightTrigger;
  67069. },
  67070. set: function (newValue) {
  67071. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  67072. this._onrighttriggerchanged(newValue);
  67073. }
  67074. this._rightTrigger = newValue;
  67075. },
  67076. enumerable: true,
  67077. configurable: true
  67078. });
  67079. Xbox360Pad.prototype.onbuttondown = function (callback) {
  67080. this._onbuttondown = callback;
  67081. };
  67082. Xbox360Pad.prototype.onbuttonup = function (callback) {
  67083. this._onbuttonup = callback;
  67084. };
  67085. Xbox360Pad.prototype.ondpaddown = function (callback) {
  67086. this._ondpaddown = callback;
  67087. };
  67088. Xbox360Pad.prototype.ondpadup = function (callback) {
  67089. this._ondpadup = callback;
  67090. };
  67091. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  67092. if (newValue !== currentValue) {
  67093. if (newValue === 1) {
  67094. if (this._onbuttondown) {
  67095. this._onbuttondown(buttonType);
  67096. }
  67097. this.onButtonDownObservable.notifyObservers(buttonType);
  67098. }
  67099. if (newValue === 0) {
  67100. if (this._onbuttonup) {
  67101. this._onbuttonup(buttonType);
  67102. }
  67103. this.onButtonUpObservable.notifyObservers(buttonType);
  67104. }
  67105. }
  67106. return newValue;
  67107. };
  67108. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  67109. if (newValue !== currentValue) {
  67110. if (newValue === 1) {
  67111. if (this._ondpaddown) {
  67112. this._ondpaddown(buttonType);
  67113. }
  67114. this.onPadDownObservable.notifyObservers(buttonType);
  67115. }
  67116. if (newValue === 0) {
  67117. if (this._ondpadup) {
  67118. this._ondpadup(buttonType);
  67119. }
  67120. this.onPadUpObservable.notifyObservers(buttonType);
  67121. }
  67122. }
  67123. return newValue;
  67124. };
  67125. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  67126. get: function () {
  67127. return this._buttonA;
  67128. },
  67129. set: function (value) {
  67130. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  67131. },
  67132. enumerable: true,
  67133. configurable: true
  67134. });
  67135. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  67136. get: function () {
  67137. return this._buttonB;
  67138. },
  67139. set: function (value) {
  67140. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  67141. },
  67142. enumerable: true,
  67143. configurable: true
  67144. });
  67145. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  67146. get: function () {
  67147. return this._buttonX;
  67148. },
  67149. set: function (value) {
  67150. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  67151. },
  67152. enumerable: true,
  67153. configurable: true
  67154. });
  67155. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  67156. get: function () {
  67157. return this._buttonY;
  67158. },
  67159. set: function (value) {
  67160. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  67161. },
  67162. enumerable: true,
  67163. configurable: true
  67164. });
  67165. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  67166. get: function () {
  67167. return this._buttonStart;
  67168. },
  67169. set: function (value) {
  67170. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  67171. },
  67172. enumerable: true,
  67173. configurable: true
  67174. });
  67175. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  67176. get: function () {
  67177. return this._buttonBack;
  67178. },
  67179. set: function (value) {
  67180. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  67181. },
  67182. enumerable: true,
  67183. configurable: true
  67184. });
  67185. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  67186. get: function () {
  67187. return this._buttonLB;
  67188. },
  67189. set: function (value) {
  67190. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  67191. },
  67192. enumerable: true,
  67193. configurable: true
  67194. });
  67195. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  67196. get: function () {
  67197. return this._buttonRB;
  67198. },
  67199. set: function (value) {
  67200. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  67201. },
  67202. enumerable: true,
  67203. configurable: true
  67204. });
  67205. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  67206. get: function () {
  67207. return this._buttonLeftStick;
  67208. },
  67209. set: function (value) {
  67210. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  67211. },
  67212. enumerable: true,
  67213. configurable: true
  67214. });
  67215. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  67216. get: function () {
  67217. return this._buttonRightStick;
  67218. },
  67219. set: function (value) {
  67220. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  67221. },
  67222. enumerable: true,
  67223. configurable: true
  67224. });
  67225. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  67226. get: function () {
  67227. return this._dPadUp;
  67228. },
  67229. set: function (value) {
  67230. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  67231. },
  67232. enumerable: true,
  67233. configurable: true
  67234. });
  67235. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  67236. get: function () {
  67237. return this._dPadDown;
  67238. },
  67239. set: function (value) {
  67240. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  67241. },
  67242. enumerable: true,
  67243. configurable: true
  67244. });
  67245. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  67246. get: function () {
  67247. return this._dPadLeft;
  67248. },
  67249. set: function (value) {
  67250. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  67251. },
  67252. enumerable: true,
  67253. configurable: true
  67254. });
  67255. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  67256. get: function () {
  67257. return this._dPadRight;
  67258. },
  67259. set: function (value) {
  67260. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  67261. },
  67262. enumerable: true,
  67263. configurable: true
  67264. });
  67265. Xbox360Pad.prototype.update = function () {
  67266. _super.prototype.update.call(this);
  67267. if (this._isXboxOnePad) {
  67268. this.buttonA = this.browserGamepad.buttons[0].value;
  67269. this.buttonB = this.browserGamepad.buttons[1].value;
  67270. this.buttonX = this.browserGamepad.buttons[2].value;
  67271. this.buttonY = this.browserGamepad.buttons[3].value;
  67272. this.buttonLB = this.browserGamepad.buttons[4].value;
  67273. this.buttonRB = this.browserGamepad.buttons[5].value;
  67274. this.leftTrigger = this.browserGamepad.axes[2];
  67275. this.rightTrigger = this.browserGamepad.axes[5];
  67276. this.buttonBack = this.browserGamepad.buttons[9].value;
  67277. this.buttonStart = this.browserGamepad.buttons[8].value;
  67278. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  67279. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  67280. this.dPadUp = this.browserGamepad.buttons[11].value;
  67281. this.dPadDown = this.browserGamepad.buttons[12].value;
  67282. this.dPadLeft = this.browserGamepad.buttons[13].value;
  67283. this.dPadRight = this.browserGamepad.buttons[14].value;
  67284. }
  67285. else {
  67286. this.buttonA = this.browserGamepad.buttons[0].value;
  67287. this.buttonB = this.browserGamepad.buttons[1].value;
  67288. this.buttonX = this.browserGamepad.buttons[2].value;
  67289. this.buttonY = this.browserGamepad.buttons[3].value;
  67290. this.buttonLB = this.browserGamepad.buttons[4].value;
  67291. this.buttonRB = this.browserGamepad.buttons[5].value;
  67292. this.leftTrigger = this.browserGamepad.buttons[6].value;
  67293. this.rightTrigger = this.browserGamepad.buttons[7].value;
  67294. this.buttonBack = this.browserGamepad.buttons[8].value;
  67295. this.buttonStart = this.browserGamepad.buttons[9].value;
  67296. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  67297. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  67298. this.dPadUp = this.browserGamepad.buttons[12].value;
  67299. this.dPadDown = this.browserGamepad.buttons[13].value;
  67300. this.dPadLeft = this.browserGamepad.buttons[14].value;
  67301. this.dPadRight = this.browserGamepad.buttons[15].value;
  67302. }
  67303. };
  67304. Xbox360Pad.prototype.dispose = function () {
  67305. _super.prototype.dispose.call(this);
  67306. this.onButtonDownObservable.clear();
  67307. this.onButtonUpObservable.clear();
  67308. this.onPadDownObservable.clear();
  67309. this.onPadUpObservable.clear();
  67310. };
  67311. return Xbox360Pad;
  67312. }(BABYLON.Gamepad));
  67313. BABYLON.Xbox360Pad = Xbox360Pad;
  67314. })(BABYLON || (BABYLON = {}));
  67315. //# sourceMappingURL=babylon.xboxGamepad.js.map
  67316. "use strict";
  67317. var BABYLON;
  67318. (function (BABYLON) {
  67319. var PoseEnabledControllerType;
  67320. (function (PoseEnabledControllerType) {
  67321. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  67322. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  67323. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  67324. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  67325. /**
  67326. * Google Daydream
  67327. */
  67328. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  67329. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  67330. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  67331. var PoseEnabledControllerHelper = /** @class */ (function () {
  67332. function PoseEnabledControllerHelper() {
  67333. }
  67334. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  67335. // Oculus Touch
  67336. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  67337. return new BABYLON.OculusTouchController(vrGamepad);
  67338. }
  67339. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  67340. return new BABYLON.WindowsMotionController(vrGamepad);
  67341. }
  67342. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  67343. return new BABYLON.ViveController(vrGamepad);
  67344. }
  67345. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  67346. return new BABYLON.GearVRController(vrGamepad);
  67347. }
  67348. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  67349. return new BABYLON.DaydreamController(vrGamepad);
  67350. }
  67351. else {
  67352. return new BABYLON.GenericController(vrGamepad);
  67353. }
  67354. };
  67355. return PoseEnabledControllerHelper;
  67356. }());
  67357. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  67358. var PoseEnabledController = /** @class */ (function (_super) {
  67359. __extends(PoseEnabledController, _super);
  67360. function PoseEnabledController(browserGamepad) {
  67361. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  67362. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  67363. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  67364. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  67365. // Represents device position and rotation in babylon space
  67366. _this.devicePosition = BABYLON.Vector3.Zero();
  67367. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  67368. _this.deviceScaleFactor = 1;
  67369. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  67370. _this._deviceToWorld = BABYLON.Matrix.Identity();
  67371. /**
  67372. * Node to be used when casting a ray from the controller
  67373. */
  67374. _this._pointingPoseNode = null;
  67375. _this._workingMatrix = BABYLON.Matrix.Identity();
  67376. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  67377. _this.controllerType = PoseEnabledControllerType.GENERIC;
  67378. _this.position = BABYLON.Vector3.Zero();
  67379. _this.rotationQuaternion = new BABYLON.Quaternion();
  67380. _this._calculatedPosition = BABYLON.Vector3.Zero();
  67381. _this._calculatedRotation = new BABYLON.Quaternion();
  67382. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  67383. return _this;
  67384. }
  67385. PoseEnabledController.prototype.update = function () {
  67386. _super.prototype.update.call(this);
  67387. var pose = this.browserGamepad.pose;
  67388. this.updateFromDevice(pose);
  67389. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  67390. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  67391. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  67392. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  67393. if (this._mesh) {
  67394. this._mesh.position.copyFrom(this.devicePosition);
  67395. if (this._mesh.rotationQuaternion) {
  67396. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  67397. }
  67398. }
  67399. };
  67400. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  67401. if (poseData) {
  67402. this.rawPose = poseData;
  67403. if (poseData.position) {
  67404. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  67405. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  67406. this._deviceRoomPosition.z *= -1;
  67407. }
  67408. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  67409. this._calculatedPosition.addInPlace(this.position);
  67410. }
  67411. var pose = this.rawPose;
  67412. if (poseData.orientation && pose.orientation) {
  67413. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  67414. if (this._mesh) {
  67415. if (this._mesh.getScene().useRightHandedSystem) {
  67416. this._deviceRoomRotationQuaternion.z *= -1;
  67417. this._deviceRoomRotationQuaternion.w *= -1;
  67418. }
  67419. else {
  67420. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  67421. }
  67422. }
  67423. // if the camera is set, rotate to the camera's rotation
  67424. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  67425. }
  67426. }
  67427. };
  67428. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  67429. if (this._mesh) {
  67430. this._mesh.parent = null;
  67431. }
  67432. this._mesh = mesh;
  67433. if (this._poseControlledCamera) {
  67434. this._mesh.parent = this._poseControlledCamera;
  67435. }
  67436. if (!this._mesh.rotationQuaternion) {
  67437. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  67438. }
  67439. };
  67440. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  67441. this._poseControlledCamera = camera;
  67442. if (this._mesh) {
  67443. this._mesh.parent = this._poseControlledCamera;
  67444. }
  67445. };
  67446. PoseEnabledController.prototype.dispose = function () {
  67447. if (this._mesh) {
  67448. this._mesh.dispose();
  67449. }
  67450. this._mesh = null;
  67451. _super.prototype.dispose.call(this);
  67452. };
  67453. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  67454. get: function () {
  67455. return this._mesh;
  67456. },
  67457. enumerable: true,
  67458. configurable: true
  67459. });
  67460. PoseEnabledController.prototype.getForwardRay = function (length) {
  67461. if (length === void 0) { length = 100; }
  67462. if (!this.mesh) {
  67463. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  67464. }
  67465. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  67466. var origin = m.getTranslation();
  67467. var forward = new BABYLON.Vector3(0, 0, -1);
  67468. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67469. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67470. return new BABYLON.Ray(origin, direction, length);
  67471. };
  67472. /**
  67473. * Name of the child mesh that can be used to cast a ray from the controller
  67474. */
  67475. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  67476. return PoseEnabledController;
  67477. }(BABYLON.Gamepad));
  67478. BABYLON.PoseEnabledController = PoseEnabledController;
  67479. })(BABYLON || (BABYLON = {}));
  67480. //# sourceMappingURL=babylon.poseEnabledController.js.map
  67481. "use strict";
  67482. var BABYLON;
  67483. (function (BABYLON) {
  67484. var WebVRController = /** @class */ (function (_super) {
  67485. __extends(WebVRController, _super);
  67486. function WebVRController(vrGamepad) {
  67487. var _this = _super.call(this, vrGamepad) || this;
  67488. // Observables
  67489. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  67490. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  67491. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  67492. _this.onPadStateChangedObservable = new BABYLON.Observable();
  67493. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  67494. _this.pad = { x: 0, y: 0 };
  67495. // avoid GC, store state in a tmp object
  67496. _this._changes = {
  67497. pressChanged: false,
  67498. touchChanged: false,
  67499. valueChanged: false,
  67500. changed: false
  67501. };
  67502. _this._buttons = new Array(vrGamepad.buttons.length);
  67503. _this.hand = vrGamepad.hand;
  67504. return _this;
  67505. }
  67506. WebVRController.prototype.onButtonStateChange = function (callback) {
  67507. this._onButtonStateChange = callback;
  67508. };
  67509. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  67510. get: function () {
  67511. return this._defaultModel;
  67512. },
  67513. enumerable: true,
  67514. configurable: true
  67515. });
  67516. WebVRController.prototype.update = function () {
  67517. _super.prototype.update.call(this);
  67518. for (var index = 0; index < this._buttons.length; index++) {
  67519. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  67520. }
  67521. ;
  67522. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  67523. this.pad.x = this.leftStick.x;
  67524. this.pad.y = this.leftStick.y;
  67525. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  67526. }
  67527. };
  67528. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  67529. if (!newState) {
  67530. newState = {
  67531. pressed: false,
  67532. touched: false,
  67533. value: 0
  67534. };
  67535. }
  67536. if (!currentState) {
  67537. this._buttons[buttonIndex] = {
  67538. pressed: newState.pressed,
  67539. touched: newState.touched,
  67540. value: newState.value
  67541. };
  67542. return;
  67543. }
  67544. this._checkChanges(newState, currentState);
  67545. if (this._changes.changed) {
  67546. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  67547. this._handleButtonChange(buttonIndex, newState, this._changes);
  67548. }
  67549. this._buttons[buttonIndex].pressed = newState.pressed;
  67550. this._buttons[buttonIndex].touched = newState.touched;
  67551. // oculus triggers are never 0, thou not touched.
  67552. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  67553. };
  67554. WebVRController.prototype._checkChanges = function (newState, currentState) {
  67555. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  67556. this._changes.touchChanged = newState.touched !== currentState.touched;
  67557. this._changes.valueChanged = newState.value !== currentState.value;
  67558. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  67559. return this._changes;
  67560. };
  67561. WebVRController.prototype.dispose = function () {
  67562. _super.prototype.dispose.call(this);
  67563. this.onTriggerStateChangedObservable.clear();
  67564. this.onMainButtonStateChangedObservable.clear();
  67565. this.onSecondaryButtonStateChangedObservable.clear();
  67566. this.onPadStateChangedObservable.clear();
  67567. this.onPadValuesChangedObservable.clear();
  67568. };
  67569. return WebVRController;
  67570. }(BABYLON.PoseEnabledController));
  67571. BABYLON.WebVRController = WebVRController;
  67572. })(BABYLON || (BABYLON = {}));
  67573. //# sourceMappingURL=babylon.webVRController.js.map
  67574. "use strict";
  67575. var BABYLON;
  67576. (function (BABYLON) {
  67577. var OculusTouchController = /** @class */ (function (_super) {
  67578. __extends(OculusTouchController, _super);
  67579. function OculusTouchController(vrGamepad) {
  67580. var _this = _super.call(this, vrGamepad) || this;
  67581. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  67582. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  67583. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  67584. return _this;
  67585. }
  67586. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67587. var _this = this;
  67588. var meshName;
  67589. // Hand
  67590. if (this.hand === 'left') {
  67591. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  67592. }
  67593. else {
  67594. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  67595. }
  67596. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  67597. /*
  67598. Parent Mesh name: oculus_touch_left
  67599. - body
  67600. - trigger
  67601. - thumbstick
  67602. - grip
  67603. - button_y
  67604. - button_x
  67605. - button_enter
  67606. */
  67607. _this._defaultModel = newMeshes[1];
  67608. _this.attachToMesh(_this._defaultModel);
  67609. if (meshLoaded) {
  67610. meshLoaded(_this._defaultModel);
  67611. }
  67612. });
  67613. };
  67614. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  67615. // helper getters for left and right hand.
  67616. get: function () {
  67617. if (this.hand === 'right') {
  67618. return this.onMainButtonStateChangedObservable;
  67619. }
  67620. else {
  67621. throw new Error('No A button on left hand');
  67622. }
  67623. },
  67624. enumerable: true,
  67625. configurable: true
  67626. });
  67627. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  67628. get: function () {
  67629. if (this.hand === 'right') {
  67630. return this.onSecondaryButtonStateChangedObservable;
  67631. }
  67632. else {
  67633. throw new Error('No B button on left hand');
  67634. }
  67635. },
  67636. enumerable: true,
  67637. configurable: true
  67638. });
  67639. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  67640. get: function () {
  67641. if (this.hand === 'left') {
  67642. return this.onMainButtonStateChangedObservable;
  67643. }
  67644. else {
  67645. throw new Error('No X button on right hand');
  67646. }
  67647. },
  67648. enumerable: true,
  67649. configurable: true
  67650. });
  67651. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  67652. get: function () {
  67653. if (this.hand === 'left') {
  67654. return this.onSecondaryButtonStateChangedObservable;
  67655. }
  67656. else {
  67657. throw new Error('No Y button on right hand');
  67658. }
  67659. },
  67660. enumerable: true,
  67661. configurable: true
  67662. });
  67663. /*
  67664. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  67665. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  67666. 2) secondary trigger (same)
  67667. 3) A (right) X (left), touch, pressed = value
  67668. 4) B / Y
  67669. 5) thumb rest
  67670. */
  67671. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67672. var notifyObject = state; //{ state: state, changes: changes };
  67673. var triggerDirection = this.hand === 'right' ? -1 : 1;
  67674. switch (buttonIdx) {
  67675. case 0:
  67676. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67677. return;
  67678. case 1:// index trigger
  67679. if (this._defaultModel) {
  67680. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  67681. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  67682. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  67683. }
  67684. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67685. return;
  67686. case 2:// secondary trigger
  67687. if (this._defaultModel) {
  67688. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  67689. }
  67690. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  67691. return;
  67692. case 3:
  67693. if (this._defaultModel) {
  67694. if (notifyObject.pressed) {
  67695. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  67696. }
  67697. else {
  67698. (this._defaultModel.getChildren()[1]).position.y = 0;
  67699. }
  67700. }
  67701. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67702. return;
  67703. case 4:
  67704. if (this._defaultModel) {
  67705. if (notifyObject.pressed) {
  67706. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67707. }
  67708. else {
  67709. (this._defaultModel.getChildren()[2]).position.y = 0;
  67710. }
  67711. }
  67712. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67713. return;
  67714. case 5:
  67715. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  67716. return;
  67717. }
  67718. };
  67719. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  67720. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  67721. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  67722. return OculusTouchController;
  67723. }(BABYLON.WebVRController));
  67724. BABYLON.OculusTouchController = OculusTouchController;
  67725. })(BABYLON || (BABYLON = {}));
  67726. //# sourceMappingURL=babylon.oculusTouchController.js.map
  67727. "use strict";
  67728. var BABYLON;
  67729. (function (BABYLON) {
  67730. var ViveController = /** @class */ (function (_super) {
  67731. __extends(ViveController, _super);
  67732. function ViveController(vrGamepad) {
  67733. var _this = _super.call(this, vrGamepad) || this;
  67734. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  67735. _this._invertLeftStickY = true;
  67736. return _this;
  67737. }
  67738. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67739. var _this = this;
  67740. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  67741. /*
  67742. Parent Mesh name: ViveWand
  67743. - body
  67744. - r_gripper
  67745. - l_gripper
  67746. - menu_button
  67747. - system_button
  67748. - trackpad
  67749. - trigger
  67750. - LED
  67751. */
  67752. _this._defaultModel = newMeshes[1];
  67753. _this.attachToMesh(_this._defaultModel);
  67754. if (meshLoaded) {
  67755. meshLoaded(_this._defaultModel);
  67756. }
  67757. });
  67758. };
  67759. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  67760. get: function () {
  67761. return this.onMainButtonStateChangedObservable;
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  67767. get: function () {
  67768. return this.onMainButtonStateChangedObservable;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  67774. get: function () {
  67775. return this.onSecondaryButtonStateChangedObservable;
  67776. },
  67777. enumerable: true,
  67778. configurable: true
  67779. });
  67780. /**
  67781. * Vive mapping:
  67782. * 0: touchpad
  67783. * 1: trigger
  67784. * 2: left AND right buttons
  67785. * 3: menu button
  67786. */
  67787. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67788. var notifyObject = state; //{ state: state, changes: changes };
  67789. switch (buttonIdx) {
  67790. case 0:
  67791. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67792. return;
  67793. case 1:// index trigger
  67794. if (this._defaultModel) {
  67795. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67796. }
  67797. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67798. return;
  67799. case 2:// left AND right button
  67800. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67801. return;
  67802. case 3:
  67803. if (this._defaultModel) {
  67804. if (notifyObject.pressed) {
  67805. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67806. }
  67807. else {
  67808. (this._defaultModel.getChildren()[2]).position.y = 0;
  67809. }
  67810. }
  67811. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67812. return;
  67813. }
  67814. };
  67815. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67816. ViveController.MODEL_FILENAME = 'wand.babylon';
  67817. return ViveController;
  67818. }(BABYLON.WebVRController));
  67819. BABYLON.ViveController = ViveController;
  67820. })(BABYLON || (BABYLON = {}));
  67821. //# sourceMappingURL=babylon.viveController.js.map
  67822. "use strict";
  67823. var BABYLON;
  67824. (function (BABYLON) {
  67825. var GenericController = /** @class */ (function (_super) {
  67826. __extends(GenericController, _super);
  67827. function GenericController(vrGamepad) {
  67828. return _super.call(this, vrGamepad) || this;
  67829. }
  67830. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67831. var _this = this;
  67832. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67833. _this._defaultModel = newMeshes[1];
  67834. _this.attachToMesh(_this._defaultModel);
  67835. if (meshLoaded) {
  67836. meshLoaded(_this._defaultModel);
  67837. }
  67838. });
  67839. };
  67840. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67841. console.log("Button id: " + buttonIdx + "state: ");
  67842. console.dir(state);
  67843. };
  67844. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67845. GenericController.MODEL_FILENAME = 'generic.babylon';
  67846. return GenericController;
  67847. }(BABYLON.WebVRController));
  67848. BABYLON.GenericController = GenericController;
  67849. })(BABYLON || (BABYLON = {}));
  67850. //# sourceMappingURL=babylon.genericController.js.map
  67851. "use strict";
  67852. var BABYLON;
  67853. (function (BABYLON) {
  67854. var LoadedMeshInfo = /** @class */ (function () {
  67855. function LoadedMeshInfo() {
  67856. this.buttonMeshes = {};
  67857. this.axisMeshes = {};
  67858. }
  67859. return LoadedMeshInfo;
  67860. }());
  67861. var WindowsMotionController = /** @class */ (function (_super) {
  67862. __extends(WindowsMotionController, _super);
  67863. function WindowsMotionController(vrGamepad) {
  67864. var _this = _super.call(this, vrGamepad) || this;
  67865. _this._mapping = {
  67866. // Semantic button names
  67867. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67868. // A mapping of the button name to glTF model node name
  67869. // that should be transformed by button value.
  67870. buttonMeshNames: {
  67871. 'trigger': 'SELECT',
  67872. 'menu': 'MENU',
  67873. 'grip': 'GRASP',
  67874. 'thumbstick': 'THUMBSTICK_PRESS',
  67875. 'trackpad': 'TOUCHPAD_PRESS'
  67876. },
  67877. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67878. buttonObservableNames: {
  67879. 'trigger': 'onTriggerStateChangedObservable',
  67880. 'menu': 'onSecondaryButtonStateChangedObservable',
  67881. 'grip': 'onMainButtonStateChangedObservable',
  67882. 'thumbstick': 'onPadStateChangedObservable',
  67883. 'trackpad': 'onTrackpadChangedObservable'
  67884. },
  67885. // A mapping of the axis name to glTF model node name
  67886. // that should be transformed by axis value.
  67887. // This array mirrors the browserGamepad.axes array, such that
  67888. // the mesh corresponding to axis 0 is in this array index 0.
  67889. axisMeshNames: [
  67890. 'THUMBSTICK_X',
  67891. 'THUMBSTICK_Y',
  67892. 'TOUCHPAD_TOUCH_X',
  67893. 'TOUCHPAD_TOUCH_Y'
  67894. ],
  67895. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67896. };
  67897. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67898. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67899. _this.trackpad = { x: 0, y: 0 };
  67900. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67901. _this._loadedMeshInfo = null;
  67902. return _this;
  67903. }
  67904. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67905. get: function () {
  67906. return this.onTriggerStateChangedObservable;
  67907. },
  67908. enumerable: true,
  67909. configurable: true
  67910. });
  67911. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67912. get: function () {
  67913. return this.onSecondaryButtonStateChangedObservable;
  67914. },
  67915. enumerable: true,
  67916. configurable: true
  67917. });
  67918. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67919. get: function () {
  67920. return this.onMainButtonStateChangedObservable;
  67921. },
  67922. enumerable: true,
  67923. configurable: true
  67924. });
  67925. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67926. get: function () {
  67927. return this.onPadStateChangedObservable;
  67928. },
  67929. enumerable: true,
  67930. configurable: true
  67931. });
  67932. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67933. get: function () {
  67934. return this.onTrackpadChangedObservable;
  67935. },
  67936. enumerable: true,
  67937. configurable: true
  67938. });
  67939. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67940. get: function () {
  67941. return this.onTrackpadValuesChangedObservable;
  67942. },
  67943. enumerable: true,
  67944. configurable: true
  67945. });
  67946. /**
  67947. * Called once per frame by the engine.
  67948. */
  67949. WindowsMotionController.prototype.update = function () {
  67950. _super.prototype.update.call(this);
  67951. if (this.browserGamepad.axes) {
  67952. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67953. this.trackpad.x = this.browserGamepad["axes"][2];
  67954. this.trackpad.y = this.browserGamepad["axes"][3];
  67955. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67956. }
  67957. // Only need to animate axes if there is a loaded mesh
  67958. if (this._loadedMeshInfo) {
  67959. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67960. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67961. }
  67962. }
  67963. }
  67964. };
  67965. /**
  67966. * Called once for each button that changed state since the last frame
  67967. * @param buttonIdx Which button index changed
  67968. * @param state New state of the button
  67969. * @param changes Which properties on the state changed since last frame
  67970. */
  67971. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67972. var buttonName = this._mapping.buttons[buttonIdx];
  67973. if (!buttonName) {
  67974. return;
  67975. }
  67976. // Only emit events for buttons that we know how to map from index to name
  67977. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67978. if (observable) {
  67979. observable.notifyObservers(state);
  67980. }
  67981. this.lerpButtonTransform(buttonName, state.value);
  67982. };
  67983. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67984. // If there is no loaded mesh, there is nothing to transform.
  67985. if (!this._loadedMeshInfo) {
  67986. return;
  67987. }
  67988. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67989. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67990. return;
  67991. }
  67992. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67993. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67994. };
  67995. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67996. if (!this._loadedMeshInfo) {
  67997. return;
  67998. }
  67999. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  68000. if (!meshInfo) {
  68001. return;
  68002. }
  68003. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  68004. return;
  68005. }
  68006. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  68007. var lerpValue = axisValue * 0.5 + 0.5;
  68008. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  68009. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  68010. };
  68011. /**
  68012. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  68013. * @param scene scene in which to add meshes
  68014. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  68015. */
  68016. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  68017. var _this = this;
  68018. if (forceDefault === void 0) { forceDefault = false; }
  68019. var path;
  68020. var filename;
  68021. // Checking if GLB loader is present
  68022. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  68023. // Determine the device specific folder based on the ID suffix
  68024. var device = 'default';
  68025. if (this.id && !forceDefault) {
  68026. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  68027. device = ((match && match[0]) || device);
  68028. }
  68029. // Hand
  68030. if (this.hand === 'left') {
  68031. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  68032. }
  68033. else {
  68034. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  68035. }
  68036. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  68037. }
  68038. else {
  68039. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  68040. path = BABYLON.GenericController.MODEL_BASE_URL;
  68041. filename = BABYLON.GenericController.MODEL_FILENAME;
  68042. }
  68043. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  68044. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  68045. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  68046. if (!_this._loadedMeshInfo) {
  68047. return;
  68048. }
  68049. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  68050. _this.attachToMesh(_this._defaultModel);
  68051. if (meshLoaded) {
  68052. meshLoaded(_this._defaultModel);
  68053. }
  68054. }, null, function (scene, message) {
  68055. BABYLON.Tools.Log(message);
  68056. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  68057. if (!forceDefault) {
  68058. _this.initControllerMesh(scene, meshLoaded, true);
  68059. }
  68060. });
  68061. };
  68062. /**
  68063. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  68064. * can be transformed by button presses and axes values, based on this._mapping.
  68065. *
  68066. * @param scene scene in which the meshes exist
  68067. * @param meshes list of meshes that make up the controller model to process
  68068. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  68069. */
  68070. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  68071. var loadedMeshInfo = null;
  68072. // Create a new mesh to contain the glTF hierarchy
  68073. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  68074. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  68075. var childMesh = null;
  68076. for (var i = 0; i < meshes.length; i++) {
  68077. var mesh = meshes[i];
  68078. if (!mesh.parent) {
  68079. // Exclude controller meshes from picking results
  68080. mesh.isPickable = false;
  68081. // Handle root node, attach to the new parentMesh
  68082. childMesh = mesh;
  68083. break;
  68084. }
  68085. }
  68086. if (childMesh) {
  68087. childMesh.setParent(parentMesh);
  68088. // Create our mesh info. Note that this method will always return non-null.
  68089. loadedMeshInfo = this.createMeshInfo(parentMesh);
  68090. }
  68091. else {
  68092. BABYLON.Tools.Warn('Could not find root node in model file.');
  68093. }
  68094. return loadedMeshInfo;
  68095. };
  68096. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  68097. var loadedMeshInfo = new LoadedMeshInfo();
  68098. var i;
  68099. loadedMeshInfo.rootNode = rootNode;
  68100. // Reset the caches
  68101. loadedMeshInfo.buttonMeshes = {};
  68102. loadedMeshInfo.axisMeshes = {};
  68103. // Button Meshes
  68104. for (i = 0; i < this._mapping.buttons.length; i++) {
  68105. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  68106. if (!buttonMeshName) {
  68107. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  68108. continue;
  68109. }
  68110. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  68111. if (!buttonMesh) {
  68112. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  68113. continue;
  68114. }
  68115. var buttonMeshInfo = {
  68116. index: i,
  68117. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  68118. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  68119. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  68120. };
  68121. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  68122. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  68123. }
  68124. else {
  68125. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  68126. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  68127. '(VALUE: ' + !!buttonMeshInfo.value +
  68128. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  68129. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  68130. ')');
  68131. }
  68132. }
  68133. // Axis Meshes
  68134. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  68135. var axisMeshName = this._mapping.axisMeshNames[i];
  68136. if (!axisMeshName) {
  68137. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  68138. continue;
  68139. }
  68140. var axisMesh = getChildByName(rootNode, axisMeshName);
  68141. if (!axisMesh) {
  68142. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  68143. continue;
  68144. }
  68145. var axisMeshInfo = {
  68146. index: i,
  68147. value: getImmediateChildByName(axisMesh, 'VALUE'),
  68148. min: getImmediateChildByName(axisMesh, 'MIN'),
  68149. max: getImmediateChildByName(axisMesh, 'MAX')
  68150. };
  68151. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  68152. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  68153. }
  68154. else {
  68155. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  68156. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  68157. '(VALUE: ' + !!axisMeshInfo.value +
  68158. ', MIN: ' + !!axisMeshInfo.min +
  68159. ', MAX:' + !!axisMeshInfo.max +
  68160. ')');
  68161. }
  68162. }
  68163. // Pointing Ray
  68164. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  68165. if (!loadedMeshInfo.pointingPoseNode) {
  68166. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  68167. }
  68168. return loadedMeshInfo;
  68169. // Look through all children recursively. This will return null if no mesh exists with the given name.
  68170. function getChildByName(node, name) {
  68171. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  68172. }
  68173. // Look through only immediate children. This will return null if no mesh exists with the given name.
  68174. function getImmediateChildByName(node, name) {
  68175. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  68176. }
  68177. };
  68178. WindowsMotionController.prototype.getForwardRay = function (length) {
  68179. if (length === void 0) { length = 100; }
  68180. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  68181. return _super.prototype.getForwardRay.call(this, length);
  68182. }
  68183. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  68184. var origin = m.getTranslation();
  68185. var forward = new BABYLON.Vector3(0, 0, -1);
  68186. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  68187. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  68188. return new BABYLON.Ray(origin, direction, length);
  68189. };
  68190. WindowsMotionController.prototype.dispose = function () {
  68191. _super.prototype.dispose.call(this);
  68192. this.onTrackpadChangedObservable.clear();
  68193. };
  68194. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  68195. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  68196. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  68197. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  68198. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  68199. return WindowsMotionController;
  68200. }(BABYLON.WebVRController));
  68201. BABYLON.WindowsMotionController = WindowsMotionController;
  68202. })(BABYLON || (BABYLON = {}));
  68203. //# sourceMappingURL=babylon.windowsMotionController.js.map
  68204. "use strict";
  68205. var BABYLON;
  68206. (function (BABYLON) {
  68207. var GearVRController = /** @class */ (function (_super) {
  68208. __extends(GearVRController, _super);
  68209. function GearVRController(vrGamepad) {
  68210. var _this = _super.call(this, vrGamepad) || this;
  68211. _this._buttonIndexToObservableNameMap = [
  68212. 'onTrackpadChangedObservable',
  68213. 'onTriggerStateChangedObservable' // Trigger
  68214. ];
  68215. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  68216. return _this;
  68217. }
  68218. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  68219. var _this = this;
  68220. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  68221. _this._defaultModel = newMeshes[1];
  68222. _this.attachToMesh(_this._defaultModel);
  68223. if (meshLoaded) {
  68224. meshLoaded(_this._defaultModel);
  68225. }
  68226. });
  68227. };
  68228. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  68229. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  68230. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  68231. // Only emit events for buttons that we know how to map from index to observable
  68232. var observable = this[observableName];
  68233. if (observable) {
  68234. observable.notifyObservers(state);
  68235. }
  68236. }
  68237. };
  68238. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  68239. GearVRController.MODEL_FILENAME = 'generic.babylon';
  68240. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  68241. return GearVRController;
  68242. }(BABYLON.WebVRController));
  68243. BABYLON.GearVRController = GearVRController;
  68244. })(BABYLON || (BABYLON = {}));
  68245. //# sourceMappingURL=babylon.gearVRController.js.map
  68246. "use strict";
  68247. var BABYLON;
  68248. (function (BABYLON) {
  68249. /**
  68250. * Google Daydream controller
  68251. */
  68252. var DaydreamController = /** @class */ (function (_super) {
  68253. __extends(DaydreamController, _super);
  68254. function DaydreamController(vrGamepad) {
  68255. var _this = _super.call(this, vrGamepad) || this;
  68256. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  68257. return _this;
  68258. }
  68259. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  68260. var _this = this;
  68261. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  68262. _this._defaultModel = newMeshes[1];
  68263. _this.attachToMesh(_this._defaultModel);
  68264. if (meshLoaded) {
  68265. meshLoaded(_this._defaultModel);
  68266. }
  68267. });
  68268. };
  68269. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  68270. // Daydream controller only has 1 GamepadButton (on the trackpad).
  68271. if (buttonIdx === 0) {
  68272. var observable = this.onTriggerStateChangedObservable;
  68273. if (observable) {
  68274. observable.notifyObservers(state);
  68275. }
  68276. }
  68277. else {
  68278. // If the app or home buttons are ever made available
  68279. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  68280. }
  68281. };
  68282. /**
  68283. * Base Url for the controller model.
  68284. */
  68285. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  68286. /**
  68287. * File name for the controller model.
  68288. */
  68289. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  68290. /**
  68291. * Gamepad Id prefix used to identify Daydream Controller.
  68292. */
  68293. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  68294. return DaydreamController;
  68295. }(BABYLON.WebVRController));
  68296. BABYLON.DaydreamController = DaydreamController;
  68297. })(BABYLON || (BABYLON = {}));
  68298. //# sourceMappingURL=babylon.daydreamController.js.map
  68299. "use strict";
  68300. var BABYLON;
  68301. (function (BABYLON) {
  68302. var FollowCamera = /** @class */ (function (_super) {
  68303. __extends(FollowCamera, _super);
  68304. function FollowCamera(name, position, scene, lockedTarget) {
  68305. if (lockedTarget === void 0) { lockedTarget = null; }
  68306. var _this = _super.call(this, name, position, scene) || this;
  68307. _this.radius = 12;
  68308. _this.rotationOffset = 0;
  68309. _this.heightOffset = 4;
  68310. _this.cameraAcceleration = 0.05;
  68311. _this.maxCameraSpeed = 20;
  68312. _this.lockedTarget = lockedTarget;
  68313. return _this;
  68314. }
  68315. FollowCamera.prototype.getRadians = function (degrees) {
  68316. return degrees * Math.PI / 180;
  68317. };
  68318. FollowCamera.prototype.follow = function (cameraTarget) {
  68319. if (!cameraTarget)
  68320. return;
  68321. var yRotation;
  68322. if (cameraTarget.rotationQuaternion) {
  68323. var rotMatrix = new BABYLON.Matrix();
  68324. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  68325. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  68326. }
  68327. else {
  68328. yRotation = cameraTarget.rotation.y;
  68329. }
  68330. var radians = this.getRadians(this.rotationOffset) + yRotation;
  68331. var targetPosition = cameraTarget.getAbsolutePosition();
  68332. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  68333. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  68334. var dx = targetX - this.position.x;
  68335. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  68336. var dz = (targetZ) - this.position.z;
  68337. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  68338. var vy = dy * this.cameraAcceleration;
  68339. var vz = dz * this.cameraAcceleration * 2;
  68340. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  68341. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  68342. }
  68343. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  68344. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  68345. }
  68346. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  68347. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  68348. }
  68349. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  68350. this.setTarget(targetPosition);
  68351. };
  68352. FollowCamera.prototype._checkInputs = function () {
  68353. _super.prototype._checkInputs.call(this);
  68354. if (this.lockedTarget) {
  68355. this.follow(this.lockedTarget);
  68356. }
  68357. };
  68358. FollowCamera.prototype.getClassName = function () {
  68359. return "FollowCamera";
  68360. };
  68361. __decorate([
  68362. BABYLON.serialize()
  68363. ], FollowCamera.prototype, "radius", void 0);
  68364. __decorate([
  68365. BABYLON.serialize()
  68366. ], FollowCamera.prototype, "rotationOffset", void 0);
  68367. __decorate([
  68368. BABYLON.serialize()
  68369. ], FollowCamera.prototype, "heightOffset", void 0);
  68370. __decorate([
  68371. BABYLON.serialize()
  68372. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  68373. __decorate([
  68374. BABYLON.serialize()
  68375. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  68376. __decorate([
  68377. BABYLON.serializeAsMeshReference("lockedTargetId")
  68378. ], FollowCamera.prototype, "lockedTarget", void 0);
  68379. return FollowCamera;
  68380. }(BABYLON.TargetCamera));
  68381. BABYLON.FollowCamera = FollowCamera;
  68382. var ArcFollowCamera = /** @class */ (function (_super) {
  68383. __extends(ArcFollowCamera, _super);
  68384. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  68385. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  68386. _this.alpha = alpha;
  68387. _this.beta = beta;
  68388. _this.radius = radius;
  68389. _this.target = target;
  68390. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  68391. _this.follow();
  68392. return _this;
  68393. }
  68394. ArcFollowCamera.prototype.follow = function () {
  68395. if (!this.target) {
  68396. return;
  68397. }
  68398. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  68399. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  68400. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  68401. var targetPosition = this.target.getAbsolutePosition();
  68402. this.position = targetPosition.add(this._cartesianCoordinates);
  68403. this.setTarget(targetPosition);
  68404. };
  68405. ArcFollowCamera.prototype._checkInputs = function () {
  68406. _super.prototype._checkInputs.call(this);
  68407. this.follow();
  68408. };
  68409. ArcFollowCamera.prototype.getClassName = function () {
  68410. return "ArcFollowCamera";
  68411. };
  68412. return ArcFollowCamera;
  68413. }(BABYLON.TargetCamera));
  68414. BABYLON.ArcFollowCamera = ArcFollowCamera;
  68415. })(BABYLON || (BABYLON = {}));
  68416. //# sourceMappingURL=babylon.followCamera.js.map
  68417. "use strict";
  68418. var BABYLON;
  68419. (function (BABYLON) {
  68420. // We're mainly based on the logic defined into the FreeCamera code
  68421. var UniversalCamera = /** @class */ (function (_super) {
  68422. __extends(UniversalCamera, _super);
  68423. //-- end properties for backward compatibility for inputs
  68424. function UniversalCamera(name, position, scene) {
  68425. var _this = _super.call(this, name, position, scene) || this;
  68426. _this.inputs.addGamepad();
  68427. return _this;
  68428. }
  68429. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  68430. //-- Begin properties for backward compatibility for inputs
  68431. get: function () {
  68432. var gamepad = this.inputs.attached["gamepad"];
  68433. if (gamepad)
  68434. return gamepad.gamepadAngularSensibility;
  68435. return 0;
  68436. },
  68437. set: function (value) {
  68438. var gamepad = this.inputs.attached["gamepad"];
  68439. if (gamepad)
  68440. gamepad.gamepadAngularSensibility = value;
  68441. },
  68442. enumerable: true,
  68443. configurable: true
  68444. });
  68445. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  68446. get: function () {
  68447. var gamepad = this.inputs.attached["gamepad"];
  68448. if (gamepad)
  68449. return gamepad.gamepadMoveSensibility;
  68450. return 0;
  68451. },
  68452. set: function (value) {
  68453. var gamepad = this.inputs.attached["gamepad"];
  68454. if (gamepad)
  68455. gamepad.gamepadMoveSensibility = value;
  68456. },
  68457. enumerable: true,
  68458. configurable: true
  68459. });
  68460. UniversalCamera.prototype.getClassName = function () {
  68461. return "UniversalCamera";
  68462. };
  68463. return UniversalCamera;
  68464. }(BABYLON.TouchCamera));
  68465. BABYLON.UniversalCamera = UniversalCamera;
  68466. })(BABYLON || (BABYLON = {}));
  68467. //# sourceMappingURL=babylon.universalCamera.js.map
  68468. "use strict";
  68469. var BABYLON;
  68470. (function (BABYLON) {
  68471. // We're mainly based on the logic defined into the FreeCamera code
  68472. var GamepadCamera = /** @class */ (function (_super) {
  68473. __extends(GamepadCamera, _super);
  68474. //-- end properties for backward compatibility for inputs
  68475. function GamepadCamera(name, position, scene) {
  68476. return _super.call(this, name, position, scene) || this;
  68477. }
  68478. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  68479. //-- Begin properties for backward compatibility for inputs
  68480. get: function () {
  68481. var gamepad = this.inputs.attached["gamepad"];
  68482. if (gamepad)
  68483. return gamepad.gamepadAngularSensibility;
  68484. return 0;
  68485. },
  68486. set: function (value) {
  68487. var gamepad = this.inputs.attached["gamepad"];
  68488. if (gamepad)
  68489. gamepad.gamepadAngularSensibility = value;
  68490. },
  68491. enumerable: true,
  68492. configurable: true
  68493. });
  68494. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  68495. get: function () {
  68496. var gamepad = this.inputs.attached["gamepad"];
  68497. if (gamepad)
  68498. return gamepad.gamepadMoveSensibility;
  68499. return 0;
  68500. },
  68501. set: function (value) {
  68502. var gamepad = this.inputs.attached["gamepad"];
  68503. if (gamepad)
  68504. gamepad.gamepadMoveSensibility = value;
  68505. },
  68506. enumerable: true,
  68507. configurable: true
  68508. });
  68509. GamepadCamera.prototype.getClassName = function () {
  68510. return "GamepadCamera";
  68511. };
  68512. return GamepadCamera;
  68513. }(BABYLON.UniversalCamera));
  68514. BABYLON.GamepadCamera = GamepadCamera;
  68515. })(BABYLON || (BABYLON = {}));
  68516. //# sourceMappingURL=babylon.gamepadCamera.js.map
  68517. "use strict";
  68518. var BABYLON;
  68519. (function (BABYLON) {
  68520. var PostProcessRenderPipelineManager = /** @class */ (function () {
  68521. function PostProcessRenderPipelineManager() {
  68522. this._renderPipelines = {};
  68523. }
  68524. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  68525. this._renderPipelines[renderPipeline._name] = renderPipeline;
  68526. };
  68527. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  68528. if (unique === void 0) { unique = false; }
  68529. var renderPipeline = this._renderPipelines[renderPipelineName];
  68530. if (!renderPipeline) {
  68531. return;
  68532. }
  68533. renderPipeline._attachCameras(cameras, unique);
  68534. };
  68535. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  68536. var renderPipeline = this._renderPipelines[renderPipelineName];
  68537. if (!renderPipeline) {
  68538. return;
  68539. }
  68540. renderPipeline._detachCameras(cameras);
  68541. };
  68542. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  68543. var renderPipeline = this._renderPipelines[renderPipelineName];
  68544. if (!renderPipeline) {
  68545. return;
  68546. }
  68547. renderPipeline._enableEffect(renderEffectName, cameras);
  68548. };
  68549. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  68550. var renderPipeline = this._renderPipelines[renderPipelineName];
  68551. if (!renderPipeline) {
  68552. return;
  68553. }
  68554. renderPipeline._disableEffect(renderEffectName, cameras);
  68555. };
  68556. PostProcessRenderPipelineManager.prototype.update = function () {
  68557. for (var renderPipelineName in this._renderPipelines) {
  68558. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  68559. var pipeline = this._renderPipelines[renderPipelineName];
  68560. if (!pipeline.isSupported) {
  68561. pipeline.dispose();
  68562. delete this._renderPipelines[renderPipelineName];
  68563. }
  68564. else {
  68565. pipeline._update();
  68566. }
  68567. }
  68568. }
  68569. };
  68570. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  68571. for (var renderPipelineName in this._renderPipelines) {
  68572. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  68573. var pipeline = this._renderPipelines[renderPipelineName];
  68574. pipeline._rebuild();
  68575. }
  68576. }
  68577. };
  68578. PostProcessRenderPipelineManager.prototype.dispose = function () {
  68579. for (var renderPipelineName in this._renderPipelines) {
  68580. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  68581. var pipeline = this._renderPipelines[renderPipelineName];
  68582. pipeline.dispose();
  68583. }
  68584. }
  68585. };
  68586. return PostProcessRenderPipelineManager;
  68587. }());
  68588. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  68589. })(BABYLON || (BABYLON = {}));
  68590. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  68591. "use strict";
  68592. var BABYLON;
  68593. (function (BABYLON) {
  68594. /**
  68595. * This represents a set of one or more post processes in Babylon.
  68596. * A post process can be used to apply a shader to a texture after it is rendered.
  68597. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  68598. */
  68599. var PostProcessRenderEffect = /** @class */ (function () {
  68600. /**
  68601. * Instantiates a post process render effect.
  68602. * A post process can be used to apply a shader to a texture after it is rendered.
  68603. * @param engine The engine the effect is tied to
  68604. * @param name The name of the effect
  68605. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  68606. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  68607. */
  68608. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  68609. this._name = name;
  68610. this._singleInstance = singleInstance || true;
  68611. this._getPostProcesses = getPostProcesses;
  68612. this._cameras = {};
  68613. this._indicesForCamera = {};
  68614. this._postProcesses = {};
  68615. }
  68616. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  68617. /**
  68618. * Checks if all the post processes in the effect are supported.
  68619. */
  68620. get: function () {
  68621. for (var index in this._postProcesses) {
  68622. for (var ppIndex in this._postProcesses[index]) {
  68623. if (!this._postProcesses[index][ppIndex].isSupported) {
  68624. return false;
  68625. }
  68626. }
  68627. }
  68628. return true;
  68629. },
  68630. enumerable: true,
  68631. configurable: true
  68632. });
  68633. /**
  68634. * Updates the current state of the effect
  68635. */
  68636. PostProcessRenderEffect.prototype._update = function () {
  68637. };
  68638. /**
  68639. * Attaches the effect on cameras
  68640. * @param cameras The camera to attach to.
  68641. */
  68642. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  68643. var _this = this;
  68644. var cameraKey;
  68645. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68646. if (!cams) {
  68647. return;
  68648. }
  68649. for (var i = 0; i < cams.length; i++) {
  68650. var camera = cams[i];
  68651. var cameraName = camera.name;
  68652. if (this._singleInstance) {
  68653. cameraKey = 0;
  68654. }
  68655. else {
  68656. cameraKey = cameraName;
  68657. }
  68658. if (!this._postProcesses[cameraKey]) {
  68659. var postProcess = this._getPostProcesses();
  68660. if (postProcess) {
  68661. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  68662. }
  68663. }
  68664. if (!this._indicesForCamera[cameraName]) {
  68665. this._indicesForCamera[cameraName] = [];
  68666. }
  68667. this._postProcesses[cameraKey].forEach(function (postProcess) {
  68668. var index = camera.attachPostProcess(postProcess);
  68669. _this._indicesForCamera[cameraName].push(index);
  68670. });
  68671. if (!this._cameras[cameraName]) {
  68672. this._cameras[cameraName] = camera;
  68673. }
  68674. }
  68675. };
  68676. /**
  68677. * Detatches the effect on cameras
  68678. * @param cameras The camera to detatch from.
  68679. */
  68680. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  68681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68682. if (!cams) {
  68683. return;
  68684. }
  68685. for (var i = 0; i < cams.length; i++) {
  68686. var camera = cams[i];
  68687. var cameraName = camera.name;
  68688. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68689. camera.detachPostProcess(postProcess);
  68690. });
  68691. if (this._cameras[cameraName]) {
  68692. //this._indicesForCamera.splice(index, 1);
  68693. this._cameras[cameraName] = null;
  68694. }
  68695. }
  68696. };
  68697. /**
  68698. * Enables the effect on given cameras
  68699. * @param cameras The camera to enable.
  68700. */
  68701. PostProcessRenderEffect.prototype._enable = function (cameras) {
  68702. var _this = this;
  68703. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68704. if (!cams) {
  68705. return;
  68706. }
  68707. for (var i = 0; i < cams.length; i++) {
  68708. var camera = cams[i];
  68709. var cameraName = camera.name;
  68710. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  68711. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  68712. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68713. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  68714. });
  68715. }
  68716. }
  68717. }
  68718. };
  68719. /**
  68720. * Disables the effect on the given cameras
  68721. * @param cameras The camera to disable.
  68722. */
  68723. PostProcessRenderEffect.prototype._disable = function (cameras) {
  68724. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68725. if (!cams) {
  68726. return;
  68727. }
  68728. for (var i = 0; i < cams.length; i++) {
  68729. var camera = cams[i];
  68730. var cameraName = camera.name;
  68731. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  68732. camera.detachPostProcess(postProcess);
  68733. });
  68734. }
  68735. };
  68736. /**
  68737. * Gets a list of the post processes contained in the effect.
  68738. * @param camera The camera to get the post processes on.
  68739. * @returns The list of the post processes in the effect.
  68740. */
  68741. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  68742. if (this._singleInstance) {
  68743. return this._postProcesses[0];
  68744. }
  68745. else {
  68746. if (!camera) {
  68747. return null;
  68748. }
  68749. return this._postProcesses[camera.name];
  68750. }
  68751. };
  68752. return PostProcessRenderEffect;
  68753. }());
  68754. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  68755. })(BABYLON || (BABYLON = {}));
  68756. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  68757. "use strict";
  68758. var BABYLON;
  68759. (function (BABYLON) {
  68760. var PostProcessRenderPipeline = /** @class */ (function () {
  68761. function PostProcessRenderPipeline(engine, name) {
  68762. this.engine = engine;
  68763. this._name = name;
  68764. this._renderEffects = {};
  68765. this._renderEffectsForIsolatedPass = new Array();
  68766. this._cameras = [];
  68767. }
  68768. PostProcessRenderPipeline.prototype.getClassName = function () {
  68769. return "PostProcessRenderPipeline";
  68770. };
  68771. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  68772. get: function () {
  68773. for (var renderEffectName in this._renderEffects) {
  68774. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68775. if (!this._renderEffects[renderEffectName].isSupported) {
  68776. return false;
  68777. }
  68778. }
  68779. }
  68780. return true;
  68781. },
  68782. enumerable: true,
  68783. configurable: true
  68784. });
  68785. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68786. this._renderEffects[renderEffect._name] = renderEffect;
  68787. };
  68788. // private
  68789. PostProcessRenderPipeline.prototype._rebuild = function () {
  68790. };
  68791. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68792. var renderEffects = this._renderEffects[renderEffectName];
  68793. if (!renderEffects) {
  68794. return;
  68795. }
  68796. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68797. };
  68798. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68799. var renderEffects = this._renderEffects[renderEffectName];
  68800. if (!renderEffects) {
  68801. return;
  68802. }
  68803. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68804. };
  68805. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68806. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68807. if (!cams) {
  68808. return;
  68809. }
  68810. var indicesToDelete = [];
  68811. var i;
  68812. for (i = 0; i < cams.length; i++) {
  68813. var camera = cams[i];
  68814. var cameraName = camera.name;
  68815. if (this._cameras.indexOf(camera) === -1) {
  68816. this._cameras[cameraName] = camera;
  68817. }
  68818. else if (unique) {
  68819. indicesToDelete.push(i);
  68820. }
  68821. }
  68822. for (i = 0; i < indicesToDelete.length; i++) {
  68823. cameras.splice(indicesToDelete[i], 1);
  68824. }
  68825. for (var renderEffectName in this._renderEffects) {
  68826. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68827. this._renderEffects[renderEffectName]._attachCameras(cams);
  68828. }
  68829. }
  68830. };
  68831. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68832. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68833. if (!cams) {
  68834. return;
  68835. }
  68836. for (var renderEffectName in this._renderEffects) {
  68837. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68838. this._renderEffects[renderEffectName]._detachCameras(cams);
  68839. }
  68840. }
  68841. for (var i = 0; i < cams.length; i++) {
  68842. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68843. }
  68844. };
  68845. PostProcessRenderPipeline.prototype._update = function () {
  68846. for (var renderEffectName in this._renderEffects) {
  68847. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68848. this._renderEffects[renderEffectName]._update();
  68849. }
  68850. }
  68851. for (var i = 0; i < this._cameras.length; i++) {
  68852. var cameraName = this._cameras[i].name;
  68853. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68854. this._renderEffectsForIsolatedPass[cameraName]._update();
  68855. }
  68856. }
  68857. };
  68858. PostProcessRenderPipeline.prototype._reset = function () {
  68859. this._renderEffects = {};
  68860. this._renderEffectsForIsolatedPass = new Array();
  68861. };
  68862. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  68863. // 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)
  68864. var effectKeys = Object.keys(this._renderEffects);
  68865. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68866. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68867. if (postProcesses) {
  68868. postProcesses[0].samples = sampleCount;
  68869. return true;
  68870. }
  68871. }
  68872. return false;
  68873. };
  68874. PostProcessRenderPipeline.prototype.dispose = function () {
  68875. // Must be implemented by children
  68876. };
  68877. __decorate([
  68878. BABYLON.serialize()
  68879. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68880. return PostProcessRenderPipeline;
  68881. }());
  68882. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68883. })(BABYLON || (BABYLON = {}));
  68884. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68885. "use strict";
  68886. var BABYLON;
  68887. (function (BABYLON) {
  68888. /**
  68889. * This represents a depth renderer in Babylon.
  68890. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68891. */
  68892. var DepthRenderer = /** @class */ (function () {
  68893. /**
  68894. * Instantiates a depth renderer
  68895. * @param scene The scene the renderer belongs to
  68896. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68897. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68898. */
  68899. function DepthRenderer(scene, type, camera) {
  68900. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68901. if (camera === void 0) { camera = null; }
  68902. var _this = this;
  68903. this._scene = scene;
  68904. this._camera = camera;
  68905. var engine = scene.getEngine();
  68906. // Render target
  68907. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68908. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68909. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68910. this._depthMap.refreshRate = 1;
  68911. this._depthMap.renderParticles = false;
  68912. this._depthMap.renderList = null;
  68913. // Camera to get depth map from to support multiple concurrent cameras
  68914. this._depthMap.activeCamera = this._camera;
  68915. this._depthMap.ignoreCameraViewport = true;
  68916. this._depthMap.useCameraPostProcesses = false;
  68917. // set default depth value to 1.0 (far away)
  68918. this._depthMap.onClearObservable.add(function (engine) {
  68919. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68920. });
  68921. // Custom render function
  68922. var renderSubMesh = function (subMesh) {
  68923. var mesh = subMesh.getRenderingMesh();
  68924. var scene = _this._scene;
  68925. var engine = scene.getEngine();
  68926. var material = subMesh.getMaterial();
  68927. if (!material) {
  68928. return;
  68929. }
  68930. // Culling and reverse (right handed system)
  68931. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68932. // Managing instances
  68933. var batch = mesh._getInstancesRenderList(subMesh._id);
  68934. if (batch.mustReturn) {
  68935. return;
  68936. }
  68937. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68938. var camera = _this._camera || scene.activeCamera;
  68939. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68940. engine.enableEffect(_this._effect);
  68941. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68942. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68943. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68944. // Alpha test
  68945. if (material && material.needAlphaTesting()) {
  68946. var alphaTexture = material.getAlphaTestTexture();
  68947. if (alphaTexture) {
  68948. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68949. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68950. }
  68951. }
  68952. // Bones
  68953. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68954. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68955. }
  68956. // Draw
  68957. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68958. }
  68959. };
  68960. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68961. var index;
  68962. if (depthOnlySubMeshes.length) {
  68963. engine.setColorWrite(false);
  68964. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68965. renderSubMesh(depthOnlySubMeshes.data[index]);
  68966. }
  68967. engine.setColorWrite(true);
  68968. }
  68969. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68970. renderSubMesh(opaqueSubMeshes.data[index]);
  68971. }
  68972. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68973. renderSubMesh(alphaTestSubMeshes.data[index]);
  68974. }
  68975. };
  68976. }
  68977. /**
  68978. * Creates the depth rendering effect and checks if the effect is ready.
  68979. * @param subMesh The submesh to be used to render the depth map of
  68980. * @param useInstances If multiple world instances should be used
  68981. * @returns if the depth renderer is ready to render the depth map
  68982. */
  68983. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68984. var material = subMesh.getMaterial();
  68985. if (material.disableDepthWrite) {
  68986. return false;
  68987. }
  68988. var defines = [];
  68989. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68990. var mesh = subMesh.getMesh();
  68991. // Alpha test
  68992. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68993. defines.push("#define ALPHATEST");
  68994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68995. attribs.push(BABYLON.VertexBuffer.UVKind);
  68996. defines.push("#define UV1");
  68997. }
  68998. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68999. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69000. defines.push("#define UV2");
  69001. }
  69002. }
  69003. // Bones
  69004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69007. if (mesh.numBoneInfluencers > 4) {
  69008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69010. }
  69011. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69012. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  69013. }
  69014. else {
  69015. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69016. }
  69017. // Instances
  69018. if (useInstances) {
  69019. defines.push("#define INSTANCES");
  69020. attribs.push("world0");
  69021. attribs.push("world1");
  69022. attribs.push("world2");
  69023. attribs.push("world3");
  69024. }
  69025. // Get correct effect
  69026. var join = defines.join("\n");
  69027. if (this._cachedDefines !== join) {
  69028. this._cachedDefines = join;
  69029. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  69030. }
  69031. return this._effect.isReady();
  69032. };
  69033. /**
  69034. * Gets the texture which the depth map will be written to.
  69035. * @returns The depth map texture
  69036. */
  69037. DepthRenderer.prototype.getDepthMap = function () {
  69038. return this._depthMap;
  69039. };
  69040. /**
  69041. * Disposes of the depth renderer.
  69042. */
  69043. DepthRenderer.prototype.dispose = function () {
  69044. this._depthMap.dispose();
  69045. };
  69046. return DepthRenderer;
  69047. }());
  69048. BABYLON.DepthRenderer = DepthRenderer;
  69049. })(BABYLON || (BABYLON = {}));
  69050. //# sourceMappingURL=babylon.depthRenderer.js.map
  69051. "use strict";
  69052. var BABYLON;
  69053. (function (BABYLON) {
  69054. var SSAORenderingPipeline = /** @class */ (function (_super) {
  69055. __extends(SSAORenderingPipeline, _super);
  69056. /**
  69057. * @constructor
  69058. * @param {string} name - The rendering pipeline name
  69059. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69060. * @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 }
  69061. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69062. */
  69063. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  69064. var _this = _super.call(this, scene.getEngine(), name) || this;
  69065. // Members
  69066. /**
  69067. * The PassPostProcess id in the pipeline that contains the original scene color
  69068. */
  69069. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  69070. /**
  69071. * The SSAO PostProcess id in the pipeline
  69072. */
  69073. _this.SSAORenderEffect = "SSAORenderEffect";
  69074. /**
  69075. * The horizontal blur PostProcess id in the pipeline
  69076. */
  69077. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  69078. /**
  69079. * The vertical blur PostProcess id in the pipeline
  69080. */
  69081. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  69082. /**
  69083. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  69084. */
  69085. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  69086. /**
  69087. * The output strength of the SSAO post-process. Default value is 1.0.
  69088. */
  69089. _this.totalStrength = 1.0;
  69090. /**
  69091. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  69092. */
  69093. _this.radius = 0.0001;
  69094. /**
  69095. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  69096. * Must not be equal to fallOff and superior to fallOff.
  69097. * Default value is 0.975
  69098. */
  69099. _this.area = 0.0075;
  69100. /**
  69101. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  69102. * Must not be equal to area and inferior to area.
  69103. * Default value is 0.0
  69104. */
  69105. _this.fallOff = 0.000001;
  69106. /**
  69107. * The base color of the SSAO post-process
  69108. * The final result is "base + ssao" between [0, 1]
  69109. */
  69110. _this.base = 0.5;
  69111. _this._firstUpdate = true;
  69112. _this._scene = scene;
  69113. // Set up assets
  69114. _this._createRandomTexture();
  69115. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  69116. var ssaoRatio = ratio.ssaoRatio || ratio;
  69117. var combineRatio = ratio.combineRatio || ratio;
  69118. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  69119. _this._createSSAOPostProcess(ssaoRatio);
  69120. _this._createBlurPostProcess(ssaoRatio);
  69121. _this._createSSAOCombinePostProcess(combineRatio);
  69122. // Set up pipeline
  69123. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  69124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  69125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  69126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  69127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  69128. // Finish
  69129. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69130. if (cameras)
  69131. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69132. return _this;
  69133. }
  69134. // Public Methods
  69135. /**
  69136. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  69137. */
  69138. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69139. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69140. for (var i = 0; i < this._scene.cameras.length; i++) {
  69141. var camera = this._scene.cameras[i];
  69142. this._originalColorPostProcess.dispose(camera);
  69143. this._ssaoPostProcess.dispose(camera);
  69144. this._blurHPostProcess.dispose(camera);
  69145. this._blurVPostProcess.dispose(camera);
  69146. this._ssaoCombinePostProcess.dispose(camera);
  69147. }
  69148. this._randomTexture.dispose();
  69149. if (disableDepthRender)
  69150. this._scene.disableDepthRenderer();
  69151. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69152. _super.prototype.dispose.call(this);
  69153. };
  69154. // Private Methods
  69155. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  69156. var _this = this;
  69157. var size = 16;
  69158. 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);
  69159. 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);
  69160. this._blurHPostProcess.onActivateObservable.add(function () {
  69161. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  69162. _this._blurHPostProcess.kernel = size * dw;
  69163. });
  69164. this._blurVPostProcess.onActivateObservable.add(function () {
  69165. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  69166. _this._blurVPostProcess.kernel = size * dw;
  69167. });
  69168. };
  69169. SSAORenderingPipeline.prototype._rebuild = function () {
  69170. this._firstUpdate = true;
  69171. _super.prototype._rebuild.call(this);
  69172. };
  69173. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  69174. var _this = this;
  69175. var numSamples = 16;
  69176. var sampleSphere = [
  69177. 0.5381, 0.1856, -0.4319,
  69178. 0.1379, 0.2486, 0.4430,
  69179. 0.3371, 0.5679, -0.0057,
  69180. -0.6999, -0.0451, -0.0019,
  69181. 0.0689, -0.1598, -0.8547,
  69182. 0.0560, 0.0069, -0.1843,
  69183. -0.0146, 0.1402, 0.0762,
  69184. 0.0100, -0.1924, -0.0344,
  69185. -0.3577, -0.5301, -0.4358,
  69186. -0.3169, 0.1063, 0.0158,
  69187. 0.0103, -0.5869, 0.0046,
  69188. -0.0897, -0.4940, 0.3287,
  69189. 0.7119, -0.0154, -0.0918,
  69190. -0.0533, 0.0596, -0.5411,
  69191. 0.0352, -0.0631, 0.5460,
  69192. -0.4776, 0.2847, -0.0271
  69193. ];
  69194. var samplesFactor = 1.0 / numSamples;
  69195. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  69196. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  69197. "area", "fallOff", "base", "range", "viewport"
  69198. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  69199. this._ssaoPostProcess.onApply = function (effect) {
  69200. if (_this._firstUpdate) {
  69201. effect.setArray3("sampleSphere", sampleSphere);
  69202. effect.setFloat("samplesFactor", samplesFactor);
  69203. effect.setFloat("randTextureTiles", 4.0);
  69204. }
  69205. effect.setFloat("totalStrength", _this.totalStrength);
  69206. effect.setFloat("radius", _this.radius);
  69207. effect.setFloat("area", _this.area);
  69208. effect.setFloat("fallOff", _this.fallOff);
  69209. effect.setFloat("base", _this.base);
  69210. effect.setTexture("textureSampler", _this._depthTexture);
  69211. effect.setTexture("randomSampler", _this._randomTexture);
  69212. };
  69213. };
  69214. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  69215. var _this = this;
  69216. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69217. this._ssaoCombinePostProcess.onApply = function (effect) {
  69218. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  69219. };
  69220. };
  69221. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  69222. var size = 512;
  69223. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69224. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69225. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69226. var context = this._randomTexture.getContext();
  69227. var rand = function (min, max) {
  69228. return Math.random() * (max - min) + min;
  69229. };
  69230. var randVector = BABYLON.Vector3.Zero();
  69231. for (var x = 0; x < size; x++) {
  69232. for (var y = 0; y < size; y++) {
  69233. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  69234. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  69235. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  69236. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  69237. context.fillRect(x, y, 1, 1);
  69238. }
  69239. }
  69240. this._randomTexture.update(false);
  69241. };
  69242. __decorate([
  69243. BABYLON.serialize()
  69244. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  69245. __decorate([
  69246. BABYLON.serialize()
  69247. ], SSAORenderingPipeline.prototype, "radius", void 0);
  69248. __decorate([
  69249. BABYLON.serialize()
  69250. ], SSAORenderingPipeline.prototype, "area", void 0);
  69251. __decorate([
  69252. BABYLON.serialize()
  69253. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  69254. __decorate([
  69255. BABYLON.serialize()
  69256. ], SSAORenderingPipeline.prototype, "base", void 0);
  69257. return SSAORenderingPipeline;
  69258. }(BABYLON.PostProcessRenderPipeline));
  69259. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  69260. })(BABYLON || (BABYLON = {}));
  69261. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  69262. "use strict";
  69263. var BABYLON;
  69264. (function (BABYLON) {
  69265. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  69266. __extends(SSAO2RenderingPipeline, _super);
  69267. /**
  69268. * @constructor
  69269. * @param {string} name - The rendering pipeline name
  69270. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69271. * @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 }
  69272. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69273. */
  69274. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  69275. var _this = _super.call(this, scene.getEngine(), name) || this;
  69276. // Members
  69277. /**
  69278. * The PassPostProcess id in the pipeline that contains the original scene color
  69279. */
  69280. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  69281. /**
  69282. * The SSAO PostProcess id in the pipeline
  69283. */
  69284. _this.SSAORenderEffect = "SSAORenderEffect";
  69285. /**
  69286. * The horizontal blur PostProcess id in the pipeline
  69287. */
  69288. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  69289. /**
  69290. * The vertical blur PostProcess id in the pipeline
  69291. */
  69292. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  69293. /**
  69294. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  69295. */
  69296. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  69297. /**
  69298. * The output strength of the SSAO post-process. Default value is 1.0.
  69299. */
  69300. _this.totalStrength = 1.0;
  69301. /**
  69302. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  69303. */
  69304. _this.maxZ = 100.0;
  69305. /**
  69306. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  69307. */
  69308. _this.minZAspect = 0.2;
  69309. /**
  69310. * Number of samples used for the SSAO calculations. Default value is 8
  69311. */
  69312. _this._samples = 8;
  69313. /**
  69314. * Are we using bilateral blur ?
  69315. */
  69316. _this._expensiveBlur = true;
  69317. /**
  69318. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  69319. */
  69320. _this.radius = 2.0;
  69321. /**
  69322. * The base color of the SSAO post-process
  69323. * The final result is "base + ssao" between [0, 1]
  69324. */
  69325. _this.base = 0.1;
  69326. _this._firstUpdate = true;
  69327. _this._scene = scene;
  69328. if (!_this.isSupported) {
  69329. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  69330. return _this;
  69331. }
  69332. var ssaoRatio = ratio.ssaoRatio || ratio;
  69333. var blurRatio = ratio.blurRatio || ratio;
  69334. // Set up assets
  69335. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  69336. _this._createRandomTexture();
  69337. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  69338. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  69339. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  69340. _this._createSSAOPostProcess(1.0);
  69341. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  69342. _this._createSSAOCombinePostProcess(blurRatio);
  69343. // Set up pipeline
  69344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  69345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  69346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  69347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  69348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  69349. // Finish
  69350. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69351. if (cameras)
  69352. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69353. return _this;
  69354. }
  69355. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  69356. get: function () {
  69357. return this._samples;
  69358. },
  69359. set: function (n) {
  69360. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  69361. this._samples = n;
  69362. this._sampleSphere = this._generateHemisphere();
  69363. this._firstUpdate = true;
  69364. },
  69365. enumerable: true,
  69366. configurable: true
  69367. });
  69368. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  69369. get: function () {
  69370. return this._expensiveBlur;
  69371. },
  69372. set: function (b) {
  69373. 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"]);
  69374. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  69375. this._expensiveBlur = b;
  69376. this._firstUpdate = true;
  69377. },
  69378. enumerable: true,
  69379. configurable: true
  69380. });
  69381. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  69382. /**
  69383. * Support test.
  69384. */
  69385. get: function () {
  69386. var engine = BABYLON.Engine.LastCreatedEngine;
  69387. if (!engine) {
  69388. return false;
  69389. }
  69390. return engine.getCaps().drawBuffersExtension;
  69391. },
  69392. enumerable: true,
  69393. configurable: true
  69394. });
  69395. // Public Methods
  69396. /**
  69397. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  69398. */
  69399. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  69400. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  69401. for (var i = 0; i < this._scene.cameras.length; i++) {
  69402. var camera = this._scene.cameras[i];
  69403. this._originalColorPostProcess.dispose(camera);
  69404. this._ssaoPostProcess.dispose(camera);
  69405. this._blurHPostProcess.dispose(camera);
  69406. this._blurVPostProcess.dispose(camera);
  69407. this._ssaoCombinePostProcess.dispose(camera);
  69408. }
  69409. this._randomTexture.dispose();
  69410. if (disableGeometryBufferRenderer)
  69411. this._scene.disableGeometryBufferRenderer();
  69412. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69413. _super.prototype.dispose.call(this);
  69414. };
  69415. // Private Methods
  69416. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  69417. var _this = this;
  69418. this._samplerOffsets = [];
  69419. var expensive = this.expensiveBlur;
  69420. for (var i = -8; i < 8; i++) {
  69421. this._samplerOffsets.push(i * 2 + 0.5);
  69422. }
  69423. 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");
  69424. this._blurHPostProcess.onApply = function (effect) {
  69425. if (!_this._scene.activeCamera) {
  69426. return;
  69427. }
  69428. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  69429. effect.setFloat("near", _this._scene.activeCamera.minZ);
  69430. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  69431. effect.setFloat("radius", _this.radius);
  69432. effect.setTexture("depthSampler", _this._depthTexture);
  69433. if (_this._firstUpdate) {
  69434. effect.setArray("samplerOffsets", _this._samplerOffsets);
  69435. }
  69436. };
  69437. 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");
  69438. this._blurVPostProcess.onApply = function (effect) {
  69439. if (!_this._scene.activeCamera) {
  69440. return;
  69441. }
  69442. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  69443. effect.setFloat("near", _this._scene.activeCamera.minZ);
  69444. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  69445. effect.setFloat("radius", _this.radius);
  69446. effect.setTexture("depthSampler", _this._depthTexture);
  69447. if (_this._firstUpdate) {
  69448. effect.setArray("samplerOffsets", _this._samplerOffsets);
  69449. _this._firstUpdate = false;
  69450. }
  69451. };
  69452. };
  69453. SSAO2RenderingPipeline.prototype._rebuild = function () {
  69454. this._firstUpdate = true;
  69455. _super.prototype._rebuild.call(this);
  69456. };
  69457. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  69458. var numSamples = this.samples;
  69459. var result = [];
  69460. var vector, scale;
  69461. var rand = function (min, max) {
  69462. return Math.random() * (max - min) + min;
  69463. };
  69464. var i = 0;
  69465. while (i < numSamples) {
  69466. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  69467. vector.normalize();
  69468. scale = i / numSamples;
  69469. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  69470. vector.scaleInPlace(scale);
  69471. result.push(vector.x, vector.y, vector.z);
  69472. i++;
  69473. }
  69474. return result;
  69475. };
  69476. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  69477. var _this = this;
  69478. var numSamples = this.samples;
  69479. this._sampleSphere = this._generateHemisphere();
  69480. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  69481. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  69482. "base", "range", "projection", "near", "far", "texelSize",
  69483. "xViewport", "yViewport", "maxZ", "minZAspect"
  69484. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  69485. this._ssaoPostProcess.onApply = function (effect) {
  69486. if (_this._firstUpdate) {
  69487. effect.setArray3("sampleSphere", _this._sampleSphere);
  69488. effect.setFloat("randTextureTiles", 4.0);
  69489. }
  69490. if (!_this._scene.activeCamera) {
  69491. return;
  69492. }
  69493. effect.setFloat("samplesFactor", 1 / _this.samples);
  69494. effect.setFloat("totalStrength", _this.totalStrength);
  69495. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  69496. effect.setFloat("radius", _this.radius);
  69497. effect.setFloat("maxZ", _this.maxZ);
  69498. effect.setFloat("minZAspect", _this.minZAspect);
  69499. effect.setFloat("base", _this.base);
  69500. effect.setFloat("near", _this._scene.activeCamera.minZ);
  69501. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  69502. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  69503. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  69504. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  69505. effect.setTexture("textureSampler", _this._depthTexture);
  69506. effect.setTexture("normalSampler", _this._normalTexture);
  69507. effect.setTexture("randomSampler", _this._randomTexture);
  69508. };
  69509. };
  69510. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  69511. var _this = this;
  69512. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69513. this._ssaoCombinePostProcess.onApply = function (effect) {
  69514. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  69515. };
  69516. };
  69517. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  69518. var size = 512;
  69519. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69520. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69521. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69522. var context = this._randomTexture.getContext();
  69523. var rand = function (min, max) {
  69524. return Math.random() * (max - min) + min;
  69525. };
  69526. var randVector = BABYLON.Vector3.Zero();
  69527. for (var x = 0; x < size; x++) {
  69528. for (var y = 0; y < size; y++) {
  69529. randVector.x = rand(0.0, 1.0);
  69530. randVector.y = rand(0.0, 1.0);
  69531. randVector.z = 0.0;
  69532. randVector.normalize();
  69533. randVector.scaleInPlace(255);
  69534. randVector.x = Math.floor(randVector.x);
  69535. randVector.y = Math.floor(randVector.y);
  69536. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  69537. context.fillRect(x, y, 1, 1);
  69538. }
  69539. }
  69540. this._randomTexture.update(false);
  69541. };
  69542. __decorate([
  69543. BABYLON.serialize()
  69544. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  69545. __decorate([
  69546. BABYLON.serialize()
  69547. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  69548. __decorate([
  69549. BABYLON.serialize()
  69550. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  69551. __decorate([
  69552. BABYLON.serialize("samples")
  69553. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  69554. __decorate([
  69555. BABYLON.serialize("expensiveBlur")
  69556. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  69557. __decorate([
  69558. BABYLON.serialize()
  69559. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  69560. __decorate([
  69561. BABYLON.serialize()
  69562. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  69563. return SSAO2RenderingPipeline;
  69564. }(BABYLON.PostProcessRenderPipeline));
  69565. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  69566. })(BABYLON || (BABYLON = {}));
  69567. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  69568. "use strict";
  69569. // BABYLON.JS Chromatic Aberration GLSL Shader
  69570. // Author: Olivier Guyot
  69571. // Separates very slightly R, G and B colors on the edges of the screen
  69572. // Inspired by Francois Tarlier & Martins Upitis
  69573. var BABYLON;
  69574. (function (BABYLON) {
  69575. var LensRenderingPipeline = /** @class */ (function (_super) {
  69576. __extends(LensRenderingPipeline, _super);
  69577. /**
  69578. * @constructor
  69579. *
  69580. * Effect parameters are as follow:
  69581. * {
  69582. * chromatic_aberration: number; // from 0 to x (1 for realism)
  69583. * edge_blur: number; // from 0 to x (1 for realism)
  69584. * distortion: number; // from 0 to x (1 for realism)
  69585. * grain_amount: number; // from 0 to 1
  69586. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  69587. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  69588. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  69589. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  69590. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  69591. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  69592. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  69593. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  69594. * }
  69595. * Note: if an effect parameter is unset, effect is disabled
  69596. *
  69597. * @param {string} name - The rendering pipeline name
  69598. * @param {object} parameters - An object containing all parameters (see above)
  69599. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69600. * @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)
  69601. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69602. */
  69603. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  69604. if (ratio === void 0) { ratio = 1.0; }
  69605. var _this = _super.call(this, scene.getEngine(), name) || this;
  69606. // Lens effects can be of the following:
  69607. // - chromatic aberration (slight shift of RGB colors)
  69608. // - blur on the edge of the lens
  69609. // - lens distortion
  69610. // - depth-of-field blur & highlights enhancing
  69611. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  69612. // - grain effect (noise or custom texture)
  69613. // Two additional texture samplers are needed:
  69614. // - depth map (for depth-of-field)
  69615. // - grain texture
  69616. /**
  69617. * The chromatic aberration PostProcess id in the pipeline
  69618. */
  69619. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  69620. /**
  69621. * The highlights enhancing PostProcess id in the pipeline
  69622. */
  69623. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  69624. /**
  69625. * The depth-of-field PostProcess id in the pipeline
  69626. */
  69627. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  69628. _this._scene = scene;
  69629. // Fetch texture samplers
  69630. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  69631. if (parameters.grain_texture) {
  69632. _this._grainTexture = parameters.grain_texture;
  69633. }
  69634. else {
  69635. _this._createGrainTexture();
  69636. }
  69637. // save parameters
  69638. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  69639. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  69640. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  69641. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  69642. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  69643. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  69644. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  69645. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  69646. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  69647. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  69648. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  69649. // Create effects
  69650. _this._createChromaticAberrationPostProcess(ratio);
  69651. _this._createHighlightsPostProcess(ratio);
  69652. _this._createDepthOfFieldPostProcess(ratio / 4);
  69653. // Set up pipeline
  69654. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  69655. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  69656. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  69657. if (_this._highlightsGain === -1) {
  69658. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  69659. }
  69660. // Finish
  69661. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69662. if (cameras) {
  69663. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  69664. }
  69665. return _this;
  69666. }
  69667. // public methods (self explanatory)
  69668. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  69669. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  69670. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  69671. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  69672. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  69673. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  69674. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  69675. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  69676. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  69677. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  69678. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  69679. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  69680. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  69681. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  69682. };
  69683. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  69684. this._highlightsPostProcess.updateEffect();
  69685. };
  69686. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  69687. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  69688. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  69689. this._highlightsGain = amount;
  69690. };
  69691. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  69692. if (this._highlightsGain === -1) {
  69693. this._highlightsGain = 1.0;
  69694. }
  69695. this._highlightsThreshold = amount;
  69696. };
  69697. LensRenderingPipeline.prototype.disableHighlights = function () {
  69698. this._highlightsGain = -1;
  69699. };
  69700. /**
  69701. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  69702. */
  69703. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  69704. if (disableDepthRender === void 0) { disableDepthRender = false; }
  69705. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  69706. this._chromaticAberrationPostProcess = null;
  69707. this._highlightsPostProcess = null;
  69708. this._depthOfFieldPostProcess = null;
  69709. this._grainTexture.dispose();
  69710. if (disableDepthRender)
  69711. this._scene.disableDepthRenderer();
  69712. };
  69713. // colors shifting and distortion
  69714. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  69715. var _this = this;
  69716. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  69717. [], // samplers
  69718. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69719. this._chromaticAberrationPostProcess.onApply = function (effect) {
  69720. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  69721. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69722. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69723. effect.setFloat('radialIntensity', 1);
  69724. effect.setFloat2('direction', 17, 17);
  69725. effect.setFloat2('centerPosition', 0.5, 0.5);
  69726. };
  69727. };
  69728. // highlights enhancing
  69729. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  69730. var _this = this;
  69731. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  69732. [], // samplers
  69733. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  69734. this._highlightsPostProcess.onApply = function (effect) {
  69735. effect.setFloat('gain', _this._highlightsGain);
  69736. effect.setFloat('threshold', _this._highlightsThreshold);
  69737. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  69738. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69739. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69740. };
  69741. };
  69742. // colors shifting and distortion
  69743. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  69744. var _this = this;
  69745. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  69746. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  69747. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  69748. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69749. this._depthOfFieldPostProcess.onApply = function (effect) {
  69750. effect.setTexture("depthSampler", _this._depthTexture);
  69751. effect.setTexture("grainSampler", _this._grainTexture);
  69752. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69753. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69754. effect.setFloat('grain_amount', _this._grainAmount);
  69755. effect.setBool('blur_noise', _this._blurNoise);
  69756. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69757. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69758. effect.setFloat('distortion', _this._distortion);
  69759. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69760. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69761. effect.setFloat('aperture', _this._dofAperture);
  69762. effect.setFloat('darken', _this._dofDarken);
  69763. effect.setFloat('edge_blur', _this._edgeBlur);
  69764. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69765. if (_this._scene.activeCamera) {
  69766. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69767. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69768. }
  69769. };
  69770. };
  69771. // creates a black and white random noise texture, 512x512
  69772. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69773. var size = 512;
  69774. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69775. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69776. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69777. var context = this._grainTexture.getContext();
  69778. var rand = function (min, max) {
  69779. return Math.random() * (max - min) + min;
  69780. };
  69781. var value;
  69782. for (var x = 0; x < size; x++) {
  69783. for (var y = 0; y < size; y++) {
  69784. value = Math.floor(rand(0.42, 0.58) * 255);
  69785. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69786. context.fillRect(x, y, 1, 1);
  69787. }
  69788. }
  69789. this._grainTexture.update(false);
  69790. };
  69791. return LensRenderingPipeline;
  69792. }(BABYLON.PostProcessRenderPipeline));
  69793. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69794. })(BABYLON || (BABYLON = {}));
  69795. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69796. "use strict";
  69797. var BABYLON;
  69798. (function (BABYLON) {
  69799. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69800. __extends(StandardRenderingPipeline, _super);
  69801. /**
  69802. * @constructor
  69803. * @param {string} name - The rendering pipeline name
  69804. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69805. * @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)
  69806. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69807. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69808. */
  69809. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69810. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69811. var _this = _super.call(this, scene.getEngine(), name) || this;
  69812. _this.downSampleX4PostProcess = null;
  69813. _this.brightPassPostProcess = null;
  69814. _this.blurHPostProcesses = [];
  69815. _this.blurVPostProcesses = [];
  69816. _this.textureAdderPostProcess = null;
  69817. _this.volumetricLightPostProcess = null;
  69818. _this.volumetricLightSmoothXPostProcess = null;
  69819. _this.volumetricLightSmoothYPostProcess = null;
  69820. _this.volumetricLightMergePostProces = null;
  69821. _this.volumetricLightFinalPostProcess = null;
  69822. _this.luminancePostProcess = null;
  69823. _this.luminanceDownSamplePostProcesses = [];
  69824. _this.hdrPostProcess = null;
  69825. _this.textureAdderFinalPostProcess = null;
  69826. _this.lensFlareFinalPostProcess = null;
  69827. _this.hdrFinalPostProcess = null;
  69828. _this.lensFlarePostProcess = null;
  69829. _this.lensFlareComposePostProcess = null;
  69830. _this.motionBlurPostProcess = null;
  69831. _this.depthOfFieldPostProcess = null;
  69832. // Values
  69833. _this.brightThreshold = 1.0;
  69834. _this.blurWidth = 512.0;
  69835. _this.horizontalBlur = false;
  69836. _this.exposure = 1.0;
  69837. _this.lensTexture = null;
  69838. _this.volumetricLightCoefficient = 0.2;
  69839. _this.volumetricLightPower = 4.0;
  69840. _this.volumetricLightBlurScale = 64.0;
  69841. _this.sourceLight = null;
  69842. _this.hdrMinimumLuminance = 1.0;
  69843. _this.hdrDecreaseRate = 0.5;
  69844. _this.hdrIncreaseRate = 0.5;
  69845. _this.lensColorTexture = null;
  69846. _this.lensFlareStrength = 20.0;
  69847. _this.lensFlareGhostDispersal = 1.4;
  69848. _this.lensFlareHaloWidth = 0.7;
  69849. _this.lensFlareDistortionStrength = 16.0;
  69850. _this.lensStarTexture = null;
  69851. _this.lensFlareDirtTexture = null;
  69852. _this.depthOfFieldDistance = 10.0;
  69853. _this.depthOfFieldBlurWidth = 64.0;
  69854. _this.motionStrength = 1.0;
  69855. // IAnimatable
  69856. _this.animations = [];
  69857. _this._currentDepthOfFieldSource = null;
  69858. _this._hdrCurrentLuminance = 1.0;
  69859. // Getters and setters
  69860. _this._bloomEnabled = true;
  69861. _this._depthOfFieldEnabled = false;
  69862. _this._vlsEnabled = false;
  69863. _this._lensFlareEnabled = false;
  69864. _this._hdrEnabled = false;
  69865. _this._motionBlurEnabled = false;
  69866. _this._motionBlurSamples = 64.0;
  69867. _this._volumetricLightStepsCount = 50.0;
  69868. _this._cameras = cameras || [];
  69869. // Initialize
  69870. _this._scene = scene;
  69871. _this._basePostProcess = originalPostProcess;
  69872. _this._ratio = ratio;
  69873. // Misc
  69874. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69875. // Finish
  69876. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69877. _this._buildPipeline();
  69878. return _this;
  69879. }
  69880. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69881. get: function () {
  69882. return this._bloomEnabled;
  69883. },
  69884. set: function (enabled) {
  69885. if (this._bloomEnabled === enabled) {
  69886. return;
  69887. }
  69888. this._bloomEnabled = enabled;
  69889. this._buildPipeline();
  69890. },
  69891. enumerable: true,
  69892. configurable: true
  69893. });
  69894. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69895. get: function () {
  69896. return this._depthOfFieldEnabled;
  69897. },
  69898. set: function (enabled) {
  69899. if (this._depthOfFieldEnabled === enabled) {
  69900. return;
  69901. }
  69902. this._depthOfFieldEnabled = enabled;
  69903. this._buildPipeline();
  69904. },
  69905. enumerable: true,
  69906. configurable: true
  69907. });
  69908. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69909. get: function () {
  69910. return this._lensFlareEnabled;
  69911. },
  69912. set: function (enabled) {
  69913. if (this._lensFlareEnabled === enabled) {
  69914. return;
  69915. }
  69916. this._lensFlareEnabled = enabled;
  69917. this._buildPipeline();
  69918. },
  69919. enumerable: true,
  69920. configurable: true
  69921. });
  69922. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69923. get: function () {
  69924. return this._hdrEnabled;
  69925. },
  69926. set: function (enabled) {
  69927. if (this._hdrEnabled === enabled) {
  69928. return;
  69929. }
  69930. this._hdrEnabled = enabled;
  69931. this._buildPipeline();
  69932. },
  69933. enumerable: true,
  69934. configurable: true
  69935. });
  69936. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69937. get: function () {
  69938. return this._vlsEnabled;
  69939. },
  69940. set: function (enabled) {
  69941. if (this._vlsEnabled === enabled) {
  69942. return;
  69943. }
  69944. if (enabled) {
  69945. var geometry = this._scene.enableGeometryBufferRenderer();
  69946. if (!geometry) {
  69947. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69948. return;
  69949. }
  69950. }
  69951. this._vlsEnabled = enabled;
  69952. this._buildPipeline();
  69953. },
  69954. enumerable: true,
  69955. configurable: true
  69956. });
  69957. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69958. get: function () {
  69959. return this._motionBlurEnabled;
  69960. },
  69961. set: function (enabled) {
  69962. if (this._motionBlurEnabled === enabled) {
  69963. return;
  69964. }
  69965. this._motionBlurEnabled = enabled;
  69966. this._buildPipeline();
  69967. },
  69968. enumerable: true,
  69969. configurable: true
  69970. });
  69971. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69972. get: function () {
  69973. return this._volumetricLightStepsCount;
  69974. },
  69975. set: function (count) {
  69976. if (this.volumetricLightPostProcess) {
  69977. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69978. }
  69979. this._volumetricLightStepsCount = count;
  69980. },
  69981. enumerable: true,
  69982. configurable: true
  69983. });
  69984. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69985. get: function () {
  69986. return this._motionBlurSamples;
  69987. },
  69988. set: function (samples) {
  69989. if (this.motionBlurPostProcess) {
  69990. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69991. }
  69992. this._motionBlurSamples = samples;
  69993. },
  69994. enumerable: true,
  69995. configurable: true
  69996. });
  69997. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69998. var _this = this;
  69999. var ratio = this._ratio;
  70000. var scene = this._scene;
  70001. this._disposePostProcesses();
  70002. this._reset();
  70003. // Create pass post-process
  70004. if (!this._basePostProcess) {
  70005. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  70006. this.originalPostProcess.onApply = function (effect) {
  70007. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  70008. };
  70009. }
  70010. else {
  70011. this.originalPostProcess = this._basePostProcess;
  70012. }
  70013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  70014. this._currentDepthOfFieldSource = this.originalPostProcess;
  70015. if (this._vlsEnabled) {
  70016. // Create volumetric light
  70017. this._createVolumetricLightPostProcess(scene, ratio);
  70018. // Create volumetric light final post-process
  70019. 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);
  70020. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  70021. }
  70022. if (this._bloomEnabled) {
  70023. // Create down sample X4 post-process
  70024. this._createDownSampleX4PostProcess(scene, ratio / 2);
  70025. // Create bright pass post-process
  70026. this._createBrightPassPostProcess(scene, ratio / 2);
  70027. // Create gaussian blur post-processes (down sampling blurs)
  70028. this._createBlurPostProcesses(scene, ratio / 4, 1);
  70029. // Create texture adder post-process
  70030. this._createTextureAdderPostProcess(scene, ratio);
  70031. // Create depth-of-field source post-process
  70032. 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);
  70033. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  70034. }
  70035. if (this._lensFlareEnabled) {
  70036. // Create lens flare post-process
  70037. this._createLensFlarePostProcess(scene, ratio);
  70038. // Create depth-of-field source post-process post lens-flare and disable it now
  70039. 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);
  70040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  70041. }
  70042. if (this._hdrEnabled) {
  70043. // Create luminance
  70044. this._createLuminancePostProcesses(scene, this._floatTextureType);
  70045. // Create HDR
  70046. this._createHdrPostProcess(scene, ratio);
  70047. // Create depth-of-field source post-process post hdr and disable it now
  70048. 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);
  70049. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  70050. }
  70051. if (this._depthOfFieldEnabled) {
  70052. // Create gaussian blur used by depth-of-field
  70053. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  70054. // Create depth-of-field post-process
  70055. this._createDepthOfFieldPostProcess(scene, ratio);
  70056. }
  70057. if (this._motionBlurEnabled) {
  70058. // Create motion blur post-process
  70059. this._createMotionBlurPostProcess(scene, ratio);
  70060. }
  70061. if (this._cameras !== null) {
  70062. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70063. }
  70064. };
  70065. // Down Sample X4 Post-Processs
  70066. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  70067. var _this = this;
  70068. var downSampleX4Offsets = new Array(32);
  70069. 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);
  70070. this.downSampleX4PostProcess.onApply = function (effect) {
  70071. var id = 0;
  70072. var width = _this.downSampleX4PostProcess.width;
  70073. var height = _this.downSampleX4PostProcess.height;
  70074. for (var i = -2; i < 2; i++) {
  70075. for (var j = -2; j < 2; j++) {
  70076. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  70077. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  70078. id += 2;
  70079. }
  70080. }
  70081. effect.setArray2("dsOffsets", downSampleX4Offsets);
  70082. };
  70083. // Add to pipeline
  70084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  70085. };
  70086. // Brightpass Post-Process
  70087. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  70088. var _this = this;
  70089. var brightOffsets = new Array(8);
  70090. 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);
  70091. this.brightPassPostProcess.onApply = function (effect) {
  70092. var sU = (1.0 / _this.brightPassPostProcess.width);
  70093. var sV = (1.0 / _this.brightPassPostProcess.height);
  70094. brightOffsets[0] = -0.5 * sU;
  70095. brightOffsets[1] = 0.5 * sV;
  70096. brightOffsets[2] = 0.5 * sU;
  70097. brightOffsets[3] = 0.5 * sV;
  70098. brightOffsets[4] = -0.5 * sU;
  70099. brightOffsets[5] = -0.5 * sV;
  70100. brightOffsets[6] = 0.5 * sU;
  70101. brightOffsets[7] = -0.5 * sV;
  70102. effect.setArray2("dsOffsets", brightOffsets);
  70103. effect.setFloat("brightThreshold", _this.brightThreshold);
  70104. };
  70105. // Add to pipeline
  70106. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  70107. };
  70108. // Create blur H&V post-processes
  70109. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  70110. var _this = this;
  70111. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  70112. var engine = scene.getEngine();
  70113. 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);
  70114. 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);
  70115. blurX.onActivateObservable.add(function () {
  70116. var dw = blurX.width / engine.getRenderWidth();
  70117. blurX.kernel = _this[blurWidthKey] * dw;
  70118. });
  70119. blurY.onActivateObservable.add(function () {
  70120. var dw = blurY.height / engine.getRenderHeight();
  70121. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  70122. });
  70123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  70124. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  70125. this.blurHPostProcesses.push(blurX);
  70126. this.blurVPostProcesses.push(blurY);
  70127. };
  70128. // Create texture adder post-process
  70129. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  70130. var _this = this;
  70131. 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);
  70132. this.textureAdderPostProcess.onApply = function (effect) {
  70133. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  70134. effect.setTexture("lensSampler", _this.lensTexture);
  70135. effect.setFloat("exposure", _this.exposure);
  70136. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  70137. };
  70138. // Add to pipeline
  70139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  70140. };
  70141. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  70142. var _this = this;
  70143. var geometryRenderer = scene.enableGeometryBufferRenderer();
  70144. geometryRenderer.enablePosition = true;
  70145. var geometry = geometryRenderer.getGBuffer();
  70146. // Base post-process
  70147. 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));
  70148. var depthValues = BABYLON.Vector2.Zero();
  70149. this.volumetricLightPostProcess.onApply = function (effect) {
  70150. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  70151. var generator = _this.sourceLight.getShadowGenerator();
  70152. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  70153. effect.setTexture("positionSampler", geometry.textures[2]);
  70154. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  70155. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  70156. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  70157. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  70158. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  70159. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  70160. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  70161. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  70162. effect.setVector2("depthValues", depthValues);
  70163. }
  70164. };
  70165. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  70166. // Smooth
  70167. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  70168. // Merge
  70169. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  70170. this.volumetricLightMergePostProces.onApply = function (effect) {
  70171. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  70172. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  70173. };
  70174. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  70175. };
  70176. // Create luminance
  70177. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  70178. var _this = this;
  70179. // Create luminance
  70180. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  70181. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  70182. var offsets = [];
  70183. this.luminancePostProcess.onApply = function (effect) {
  70184. var sU = (1.0 / _this.luminancePostProcess.width);
  70185. var sV = (1.0 / _this.luminancePostProcess.height);
  70186. offsets[0] = -0.5 * sU;
  70187. offsets[1] = 0.5 * sV;
  70188. offsets[2] = 0.5 * sU;
  70189. offsets[3] = 0.5 * sV;
  70190. offsets[4] = -0.5 * sU;
  70191. offsets[5] = -0.5 * sV;
  70192. offsets[6] = 0.5 * sU;
  70193. offsets[7] = -0.5 * sV;
  70194. effect.setArray2("lumOffsets", offsets);
  70195. };
  70196. // Add to pipeline
  70197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  70198. // Create down sample luminance
  70199. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  70200. var size = Math.pow(3, i);
  70201. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  70202. if (i === 0) {
  70203. defines += "#define FINAL_DOWN_SAMPLER";
  70204. }
  70205. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  70206. this.luminanceDownSamplePostProcesses.push(postProcess);
  70207. }
  70208. // Create callbacks and add effects
  70209. var lastLuminance = this.luminancePostProcess;
  70210. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  70211. var downSampleOffsets = new Array(18);
  70212. pp.onApply = function (effect) {
  70213. if (!lastLuminance) {
  70214. return;
  70215. }
  70216. var id = 0;
  70217. for (var x = -1; x < 2; x++) {
  70218. for (var y = -1; y < 2; y++) {
  70219. downSampleOffsets[id] = x / lastLuminance.width;
  70220. downSampleOffsets[id + 1] = y / lastLuminance.height;
  70221. id += 2;
  70222. }
  70223. }
  70224. effect.setArray2("dsOffsets", downSampleOffsets);
  70225. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  70226. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  70227. lastLuminance = _this.luminancePostProcess;
  70228. }
  70229. else {
  70230. lastLuminance = pp;
  70231. }
  70232. };
  70233. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  70234. pp.onAfterRender = function (effect) {
  70235. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  70236. 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);
  70237. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  70238. };
  70239. }
  70240. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  70241. });
  70242. };
  70243. // Create HDR post-process
  70244. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  70245. var _this = this;
  70246. 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);
  70247. var outputLiminance = 1;
  70248. var time = 0;
  70249. var lastTime = 0;
  70250. this.hdrPostProcess.onApply = function (effect) {
  70251. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  70252. time += scene.getEngine().getDeltaTime();
  70253. if (outputLiminance < 0) {
  70254. outputLiminance = _this._hdrCurrentLuminance;
  70255. }
  70256. else {
  70257. var dt = (lastTime - time) / 1000.0;
  70258. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  70259. outputLiminance += _this.hdrDecreaseRate * dt;
  70260. }
  70261. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  70262. outputLiminance -= _this.hdrIncreaseRate * dt;
  70263. }
  70264. else {
  70265. outputLiminance = _this._hdrCurrentLuminance;
  70266. }
  70267. }
  70268. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  70269. effect.setFloat("averageLuminance", outputLiminance);
  70270. lastTime = time;
  70271. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  70272. };
  70273. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  70274. };
  70275. // Create lens flare post-process
  70276. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  70277. var _this = this;
  70278. 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);
  70279. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  70280. this._createBlurPostProcesses(scene, ratio / 4, 2);
  70281. 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);
  70282. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  70283. var resolution = new BABYLON.Vector2(0, 0);
  70284. // Lens flare
  70285. this.lensFlarePostProcess.onApply = function (effect) {
  70286. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  70287. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  70288. effect.setFloat("strength", _this.lensFlareStrength);
  70289. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  70290. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  70291. // Shift
  70292. resolution.x = _this.lensFlarePostProcess.width;
  70293. resolution.y = _this.lensFlarePostProcess.height;
  70294. effect.setVector2("resolution", resolution);
  70295. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  70296. };
  70297. // Compose
  70298. 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);
  70299. 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);
  70300. this.lensFlareComposePostProcess.onApply = function (effect) {
  70301. if (!_this._scene.activeCamera) {
  70302. return;
  70303. }
  70304. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  70305. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  70306. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  70307. // Lens start rotation matrix
  70308. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  70309. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  70310. 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));
  70311. camRot *= 4.0;
  70312. 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);
  70313. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  70314. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  70315. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  70316. };
  70317. };
  70318. // Create depth-of-field post-process
  70319. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  70320. var _this = this;
  70321. 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);
  70322. this.depthOfFieldPostProcess.onApply = function (effect) {
  70323. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  70324. effect.setTexture("depthSampler", _this._getDepthTexture());
  70325. effect.setFloat("distance", _this.depthOfFieldDistance);
  70326. };
  70327. // Add to pipeline
  70328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  70329. };
  70330. // Create motion blur post-process
  70331. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  70332. var _this = this;
  70333. 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);
  70334. var motionScale = 0;
  70335. var prevViewProjection = BABYLON.Matrix.Identity();
  70336. var invViewProjection = BABYLON.Matrix.Identity();
  70337. var viewProjection = BABYLON.Matrix.Identity();
  70338. var screenSize = BABYLON.Vector2.Zero();
  70339. this.motionBlurPostProcess.onApply = function (effect) {
  70340. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  70341. viewProjection.invertToRef(invViewProjection);
  70342. effect.setMatrix("inverseViewProjection", invViewProjection);
  70343. effect.setMatrix("prevViewProjection", prevViewProjection);
  70344. prevViewProjection = viewProjection;
  70345. screenSize.x = _this.motionBlurPostProcess.width;
  70346. screenSize.y = _this.motionBlurPostProcess.height;
  70347. effect.setVector2("screenSize", screenSize);
  70348. motionScale = scene.getEngine().getFps() / 60.0;
  70349. effect.setFloat("motionScale", motionScale);
  70350. effect.setFloat("motionStrength", _this.motionStrength);
  70351. effect.setTexture("depthSampler", _this._getDepthTexture());
  70352. };
  70353. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  70354. };
  70355. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  70356. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  70357. var renderer = this._scene.enableGeometryBufferRenderer();
  70358. return renderer.getGBuffer().textures[0];
  70359. }
  70360. return this._scene.enableDepthRenderer().getDepthMap();
  70361. };
  70362. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  70363. for (var i = 0; i < this._cameras.length; i++) {
  70364. var camera = this._cameras[i];
  70365. if (this.originalPostProcess) {
  70366. this.originalPostProcess.dispose(camera);
  70367. }
  70368. if (this.downSampleX4PostProcess) {
  70369. this.downSampleX4PostProcess.dispose(camera);
  70370. }
  70371. if (this.brightPassPostProcess) {
  70372. this.brightPassPostProcess.dispose(camera);
  70373. }
  70374. if (this.textureAdderPostProcess) {
  70375. this.textureAdderPostProcess.dispose(camera);
  70376. }
  70377. if (this.textureAdderFinalPostProcess) {
  70378. this.textureAdderFinalPostProcess.dispose(camera);
  70379. }
  70380. if (this.volumetricLightPostProcess) {
  70381. this.volumetricLightPostProcess.dispose(camera);
  70382. }
  70383. if (this.volumetricLightSmoothXPostProcess) {
  70384. this.volumetricLightSmoothXPostProcess.dispose(camera);
  70385. }
  70386. if (this.volumetricLightSmoothYPostProcess) {
  70387. this.volumetricLightSmoothYPostProcess.dispose(camera);
  70388. }
  70389. if (this.volumetricLightMergePostProces) {
  70390. this.volumetricLightMergePostProces.dispose(camera);
  70391. }
  70392. if (this.volumetricLightFinalPostProcess) {
  70393. this.volumetricLightFinalPostProcess.dispose(camera);
  70394. }
  70395. if (this.lensFlarePostProcess) {
  70396. this.lensFlarePostProcess.dispose(camera);
  70397. }
  70398. if (this.lensFlareComposePostProcess) {
  70399. this.lensFlareComposePostProcess.dispose(camera);
  70400. }
  70401. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  70402. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  70403. }
  70404. if (this.luminancePostProcess) {
  70405. this.luminancePostProcess.dispose(camera);
  70406. }
  70407. if (this.hdrPostProcess) {
  70408. this.hdrPostProcess.dispose(camera);
  70409. }
  70410. if (this.hdrFinalPostProcess) {
  70411. this.hdrFinalPostProcess.dispose(camera);
  70412. }
  70413. if (this.depthOfFieldPostProcess) {
  70414. this.depthOfFieldPostProcess.dispose(camera);
  70415. }
  70416. if (this.motionBlurPostProcess) {
  70417. this.motionBlurPostProcess.dispose(camera);
  70418. }
  70419. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  70420. this.blurHPostProcesses[j].dispose(camera);
  70421. }
  70422. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  70423. this.blurVPostProcesses[j].dispose(camera);
  70424. }
  70425. }
  70426. this.originalPostProcess = null;
  70427. this.downSampleX4PostProcess = null;
  70428. this.brightPassPostProcess = null;
  70429. this.textureAdderPostProcess = null;
  70430. this.textureAdderFinalPostProcess = null;
  70431. this.volumetricLightPostProcess = null;
  70432. this.volumetricLightSmoothXPostProcess = null;
  70433. this.volumetricLightSmoothYPostProcess = null;
  70434. this.volumetricLightMergePostProces = null;
  70435. this.volumetricLightFinalPostProcess = null;
  70436. this.lensFlarePostProcess = null;
  70437. this.lensFlareComposePostProcess = null;
  70438. this.luminancePostProcess = null;
  70439. this.hdrPostProcess = null;
  70440. this.hdrFinalPostProcess = null;
  70441. this.depthOfFieldPostProcess = null;
  70442. this.motionBlurPostProcess = null;
  70443. this.luminanceDownSamplePostProcesses = [];
  70444. this.blurHPostProcesses = [];
  70445. this.blurVPostProcesses = [];
  70446. };
  70447. // Dispose
  70448. StandardRenderingPipeline.prototype.dispose = function () {
  70449. this._disposePostProcesses();
  70450. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70451. _super.prototype.dispose.call(this);
  70452. };
  70453. // Serialize rendering pipeline
  70454. StandardRenderingPipeline.prototype.serialize = function () {
  70455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70456. serializationObject.customType = "StandardRenderingPipeline";
  70457. return serializationObject;
  70458. };
  70459. /**
  70460. * Static members
  70461. */
  70462. // Parse serialized pipeline
  70463. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70464. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  70465. };
  70466. // Luminance steps
  70467. StandardRenderingPipeline.LuminanceSteps = 6;
  70468. __decorate([
  70469. BABYLON.serialize()
  70470. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  70471. __decorate([
  70472. BABYLON.serialize()
  70473. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  70474. __decorate([
  70475. BABYLON.serialize()
  70476. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  70477. __decorate([
  70478. BABYLON.serialize()
  70479. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  70480. __decorate([
  70481. BABYLON.serializeAsTexture("lensTexture")
  70482. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  70483. __decorate([
  70484. BABYLON.serialize()
  70485. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  70486. __decorate([
  70487. BABYLON.serialize()
  70488. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  70489. __decorate([
  70490. BABYLON.serialize()
  70491. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  70492. __decorate([
  70493. BABYLON.serialize()
  70494. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  70495. __decorate([
  70496. BABYLON.serialize()
  70497. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  70498. __decorate([
  70499. BABYLON.serialize()
  70500. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  70501. __decorate([
  70502. BABYLON.serializeAsTexture("lensColorTexture")
  70503. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  70504. __decorate([
  70505. BABYLON.serialize()
  70506. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  70507. __decorate([
  70508. BABYLON.serialize()
  70509. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  70510. __decorate([
  70511. BABYLON.serialize()
  70512. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  70513. __decorate([
  70514. BABYLON.serialize()
  70515. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  70516. __decorate([
  70517. BABYLON.serializeAsTexture("lensStarTexture")
  70518. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  70519. __decorate([
  70520. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  70521. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  70522. __decorate([
  70523. BABYLON.serialize()
  70524. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  70525. __decorate([
  70526. BABYLON.serialize()
  70527. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  70528. __decorate([
  70529. BABYLON.serialize()
  70530. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  70531. __decorate([
  70532. BABYLON.serialize()
  70533. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  70534. __decorate([
  70535. BABYLON.serialize()
  70536. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  70537. __decorate([
  70538. BABYLON.serialize()
  70539. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  70540. __decorate([
  70541. BABYLON.serialize()
  70542. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  70543. __decorate([
  70544. BABYLON.serialize()
  70545. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  70546. __decorate([
  70547. BABYLON.serialize()
  70548. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  70549. __decorate([
  70550. BABYLON.serialize()
  70551. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  70552. __decorate([
  70553. BABYLON.serialize()
  70554. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  70555. __decorate([
  70556. BABYLON.serialize()
  70557. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  70558. return StandardRenderingPipeline;
  70559. }(BABYLON.PostProcessRenderPipeline));
  70560. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  70561. })(BABYLON || (BABYLON = {}));
  70562. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  70563. "use strict";
  70564. var BABYLON;
  70565. (function (BABYLON) {
  70566. var FxaaPostProcess = /** @class */ (function (_super) {
  70567. __extends(FxaaPostProcess, _super);
  70568. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  70569. if (camera === void 0) { camera = null; }
  70570. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70571. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  70572. _this.onApplyObservable.add(function (effect) {
  70573. var texelSize = _this.texelSize;
  70574. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  70575. });
  70576. return _this;
  70577. }
  70578. return FxaaPostProcess;
  70579. }(BABYLON.PostProcess));
  70580. BABYLON.FxaaPostProcess = FxaaPostProcess;
  70581. })(BABYLON || (BABYLON = {}));
  70582. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  70583. "use strict";
  70584. var BABYLON;
  70585. (function (BABYLON) {
  70586. /**
  70587. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  70588. */
  70589. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  70590. __extends(ChromaticAberrationPostProcess, _super);
  70591. /**
  70592. * Creates a new instance ChromaticAberrationPostProcess
  70593. * @param name The name of the effect.
  70594. * @param screenWidth The width of the screen to apply the effect on.
  70595. * @param screenHeight The height of the screen to apply the effect on.
  70596. * @param options The required width/height ratio to downsize to before computing the render pass.
  70597. * @param camera The camera to apply the render pass to.
  70598. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70599. * @param engine The engine which the post process will be applied. (default: current engine)
  70600. * @param reusable If the post process can be reused on the same frame. (default: false)
  70601. * @param textureType Type of textures used when performing the post process. (default: 0)
  70602. * @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)
  70603. */
  70604. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70605. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70606. if (blockCompilation === void 0) { blockCompilation = false; }
  70607. 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;
  70608. /**
  70609. * The amount of seperation of rgb channels (default: 30)
  70610. */
  70611. _this.aberrationAmount = 30;
  70612. /**
  70613. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  70614. */
  70615. _this.radialIntensity = 0;
  70616. /**
  70617. * 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))
  70618. */
  70619. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  70620. /**
  70621. * 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))
  70622. */
  70623. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  70624. _this.onApplyObservable.add(function (effect) {
  70625. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  70626. effect.setFloat('screen_width', screenWidth);
  70627. effect.setFloat('screen_height', screenHeight);
  70628. effect.setFloat('radialIntensity', _this.radialIntensity);
  70629. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  70630. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  70631. });
  70632. return _this;
  70633. }
  70634. return ChromaticAberrationPostProcess;
  70635. }(BABYLON.PostProcess));
  70636. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  70637. })(BABYLON || (BABYLON = {}));
  70638. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  70639. "use strict";
  70640. var BABYLON;
  70641. (function (BABYLON) {
  70642. /**
  70643. * The GrainPostProcess adds noise to the image at mid luminance levels
  70644. */
  70645. var GrainPostProcess = /** @class */ (function (_super) {
  70646. __extends(GrainPostProcess, _super);
  70647. /**
  70648. * Creates a new instance of @see GrainPostProcess
  70649. * @param name The name of the effect.
  70650. * @param options The required width/height ratio to downsize to before computing the render pass.
  70651. * @param camera The camera to apply the render pass to.
  70652. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70653. * @param engine The engine which the post process will be applied. (default: current engine)
  70654. * @param reusable If the post process can be reused on the same frame. (default: false)
  70655. * @param textureType Type of textures used when performing the post process. (default: 0)
  70656. * @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)
  70657. */
  70658. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70659. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70660. if (blockCompilation === void 0) { blockCompilation = false; }
  70661. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70662. /**
  70663. * The intensity of the grain added (default: 30)
  70664. */
  70665. _this.intensity = 30;
  70666. /**
  70667. * If the grain should be randomized on every frame
  70668. */
  70669. _this.animated = false;
  70670. _this.onApplyObservable.add(function (effect) {
  70671. effect.setFloat('intensity', _this.intensity);
  70672. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  70673. });
  70674. return _this;
  70675. }
  70676. return GrainPostProcess;
  70677. }(BABYLON.PostProcess));
  70678. BABYLON.GrainPostProcess = GrainPostProcess;
  70679. })(BABYLON || (BABYLON = {}));
  70680. //# sourceMappingURL=babylon.grainPostProcess.js.map
  70681. "use strict";
  70682. var BABYLON;
  70683. (function (BABYLON) {
  70684. /**
  70685. * The SharpenPostProcess applies a sharpen kernel to every pixel
  70686. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  70687. */
  70688. var SharpenPostProcess = /** @class */ (function (_super) {
  70689. __extends(SharpenPostProcess, _super);
  70690. /**
  70691. * Creates a new instance ConvolutionPostProcess
  70692. * @param name The name of the effect.
  70693. * @param options The required width/height ratio to downsize to before computing the render pass.
  70694. * @param camera The camera to apply the render pass to.
  70695. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70696. * @param engine The engine which the post process will be applied. (default: current engine)
  70697. * @param reusable If the post process can be reused on the same frame. (default: false)
  70698. * @param textureType Type of textures used when performing the post process. (default: 0)
  70699. * @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)
  70700. */
  70701. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70702. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70703. if (blockCompilation === void 0) { blockCompilation = false; }
  70704. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70705. /**
  70706. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  70707. */
  70708. _this.colorAmount = 1.0;
  70709. /**
  70710. * How much sharpness should be applied (default: 0.3)
  70711. */
  70712. _this.edgeAmount = 0.3;
  70713. _this.onApply = function (effect) {
  70714. effect.setFloat2("screenSize", _this.width, _this.height);
  70715. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  70716. };
  70717. return _this;
  70718. }
  70719. return SharpenPostProcess;
  70720. }(BABYLON.PostProcess));
  70721. BABYLON.SharpenPostProcess = SharpenPostProcess;
  70722. })(BABYLON || (BABYLON = {}));
  70723. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  70724. "use strict";
  70725. var BABYLON;
  70726. (function (BABYLON) {
  70727. /**
  70728. * The Blur Post Process which blurs an image based on a kernel and direction.
  70729. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  70730. */
  70731. var BlurPostProcess = /** @class */ (function (_super) {
  70732. __extends(BlurPostProcess, _super);
  70733. /**
  70734. * Creates a new instance BlurPostProcess
  70735. * @param name The name of the effect.
  70736. * @param direction The direction in which to blur the image.
  70737. * @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.
  70738. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  70739. * @param camera The camera to apply the render pass to.
  70740. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70741. * @param engine The engine which the post process will be applied. (default: current engine)
  70742. * @param reusable If the post process can be reused on the same frame. (default: false)
  70743. * @param textureType Type of textures used when performing the post process. (default: 0)
  70744. * @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)
  70745. */
  70746. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  70747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70748. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70749. if (defines === void 0) { defines = ""; }
  70750. if (blockCompilation === void 0) { blockCompilation = false; }
  70751. 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;
  70752. _this.direction = direction;
  70753. _this.blockCompilation = blockCompilation;
  70754. _this._packedFloat = false;
  70755. _this._staticDefines = "";
  70756. _this._staticDefines = defines;
  70757. _this.onApplyObservable.add(function (effect) {
  70758. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70759. });
  70760. _this.kernel = kernel;
  70761. return _this;
  70762. }
  70763. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70764. /**
  70765. * Gets the length in pixels of the blur sample region
  70766. */
  70767. get: function () {
  70768. return this._idealKernel;
  70769. },
  70770. /**
  70771. * Sets the length in pixels of the blur sample region
  70772. */
  70773. set: function (v) {
  70774. if (this._idealKernel === v) {
  70775. return;
  70776. }
  70777. v = Math.max(v, 1);
  70778. this._idealKernel = v;
  70779. this._kernel = this._nearestBestKernel(v);
  70780. if (!this.blockCompilation) {
  70781. this._updateParameters();
  70782. }
  70783. },
  70784. enumerable: true,
  70785. configurable: true
  70786. });
  70787. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70788. /**
  70789. * Gets wether or not the blur is unpacking/repacking floats
  70790. */
  70791. get: function () {
  70792. return this._packedFloat;
  70793. },
  70794. /**
  70795. * Sets wether or not the blur needs to unpack/repack floats
  70796. */
  70797. set: function (v) {
  70798. if (this._packedFloat === v) {
  70799. return;
  70800. }
  70801. this._packedFloat = v;
  70802. if (!this.blockCompilation) {
  70803. this._updateParameters();
  70804. }
  70805. },
  70806. enumerable: true,
  70807. configurable: true
  70808. });
  70809. /**
  70810. * Updates the effect with the current post process compile time values and recompiles the shader.
  70811. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70812. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70813. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70814. * @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
  70815. * @param onCompiled Called when the shader has been compiled.
  70816. * @param onError Called if there is an error when compiling a shader.
  70817. */
  70818. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70819. if (defines === void 0) { defines = null; }
  70820. if (uniforms === void 0) { uniforms = null; }
  70821. if (samplers === void 0) { samplers = null; }
  70822. this._updateParameters(onCompiled, onError);
  70823. };
  70824. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70825. // Generate sampling offsets and weights
  70826. var N = this._kernel;
  70827. var centerIndex = (N - 1) / 2;
  70828. // Generate Gaussian sampling weights over kernel
  70829. var offsets = [];
  70830. var weights = [];
  70831. var totalWeight = 0;
  70832. for (var i = 0; i < N; i++) {
  70833. var u = i / (N - 1);
  70834. var w = this._gaussianWeight(u * 2.0 - 1);
  70835. offsets[i] = (i - centerIndex);
  70836. weights[i] = w;
  70837. totalWeight += w;
  70838. }
  70839. // Normalize weights
  70840. for (var i = 0; i < weights.length; i++) {
  70841. weights[i] /= totalWeight;
  70842. }
  70843. // Optimize: combine samples to take advantage of hardware linear sampling
  70844. // Walk from left to center, combining pairs (symmetrically)
  70845. var linearSamplingWeights = [];
  70846. var linearSamplingOffsets = [];
  70847. var linearSamplingMap = [];
  70848. for (var i = 0; i <= centerIndex; i += 2) {
  70849. var j = Math.min(i + 1, Math.floor(centerIndex));
  70850. var singleCenterSample = i === j;
  70851. if (singleCenterSample) {
  70852. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70853. }
  70854. else {
  70855. var sharedCell = j === centerIndex;
  70856. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70857. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70858. if (offsetLinear === 0) {
  70859. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70860. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70861. }
  70862. else {
  70863. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70864. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70865. }
  70866. }
  70867. }
  70868. for (var i = 0; i < linearSamplingMap.length; i++) {
  70869. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70870. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70871. }
  70872. // Replace with optimized
  70873. offsets = linearSamplingOffsets;
  70874. weights = linearSamplingWeights;
  70875. // Generate shaders
  70876. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70877. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70878. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70879. var defines = "";
  70880. defines += this._staticDefines;
  70881. for (var i = 0; i < varyingCount; i++) {
  70882. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70883. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70884. }
  70885. var depCount = 0;
  70886. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70887. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70888. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70889. depCount++;
  70890. }
  70891. if (this.packedFloat) {
  70892. defines += "#define PACKEDFLOAT 1";
  70893. }
  70894. this.blockCompilation = false;
  70895. _super.prototype.updateEffect.call(this, defines, null, null, {
  70896. varyingCount: varyingCount,
  70897. depCount: depCount
  70898. }, onCompiled, onError);
  70899. };
  70900. /**
  70901. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70902. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70903. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70904. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70905. * The gaps between physical kernels are compensated for in the weighting of the samples
  70906. * @param idealKernel Ideal blur kernel.
  70907. * @return Nearest best kernel.
  70908. */
  70909. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70910. var v = Math.round(idealKernel);
  70911. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70912. var k = _a[_i];
  70913. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70914. return Math.max(k, 3);
  70915. }
  70916. }
  70917. return Math.max(v, 3);
  70918. };
  70919. /**
  70920. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70921. * @param x The point on the Gaussian distribution to sample.
  70922. * @return the value of the Gaussian function at x.
  70923. */
  70924. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70925. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70926. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70927. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70928. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70929. // truncated at around 1.3% of peak strength.
  70930. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70931. var sigma = (1 / 3);
  70932. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70933. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70934. var weight = (1.0 / denominator) * Math.exp(exponent);
  70935. return weight;
  70936. };
  70937. /**
  70938. * Generates a string that can be used as a floating point number in GLSL.
  70939. * @param x Value to print.
  70940. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70941. * @return GLSL float string.
  70942. */
  70943. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70944. if (decimalFigures === void 0) { decimalFigures = 8; }
  70945. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70946. };
  70947. return BlurPostProcess;
  70948. }(BABYLON.PostProcess));
  70949. BABYLON.BlurPostProcess = BlurPostProcess;
  70950. })(BABYLON || (BABYLON = {}));
  70951. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70952. "use strict";
  70953. var BABYLON;
  70954. (function (BABYLON) {
  70955. /**
  70956. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70957. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70958. * based on samples that have a large difference in distance than the center pixel.
  70959. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70960. */
  70961. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70962. __extends(DepthOfFieldBlurPostProcess, _super);
  70963. /**
  70964. * Creates a new instance CircleOfConfusionPostProcess
  70965. * @param name The name of the effect.
  70966. * @param scene The scene the effect belongs to.
  70967. * @param direction The direction the blur should be applied.
  70968. * @param kernel The size of the kernel used to blur.
  70969. * @param options The required width/height ratio to downsize to before computing the render pass.
  70970. * @param camera The camera to apply the render pass to.
  70971. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70972. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70973. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70974. * @param engine The engine which the post process will be applied. (default: current engine)
  70975. * @param reusable If the post process can be reused on the same frame. (default: false)
  70976. * @param textureType Type of textures used when performing the post process. (default: 0)
  70977. * @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)
  70978. */
  70979. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70980. if (imageToBlur === void 0) { imageToBlur = null; }
  70981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70982. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70983. if (blockCompilation === void 0) { blockCompilation = false; }
  70984. 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;
  70985. _this.direction = direction;
  70986. _this.onApplyObservable.add(function (effect) {
  70987. if (imageToBlur != null) {
  70988. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70989. }
  70990. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70991. if (scene.activeCamera) {
  70992. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70993. }
  70994. });
  70995. return _this;
  70996. }
  70997. return DepthOfFieldBlurPostProcess;
  70998. }(BABYLON.BlurPostProcess));
  70999. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  71000. })(BABYLON || (BABYLON = {}));
  71001. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  71002. "use strict";
  71003. var BABYLON;
  71004. (function (BABYLON) {
  71005. /**
  71006. * Options to be set when merging outputs from the default pipeline.
  71007. */
  71008. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  71009. function DepthOfFieldMergePostProcessOptions() {
  71010. }
  71011. return DepthOfFieldMergePostProcessOptions;
  71012. }());
  71013. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  71014. /**
  71015. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  71016. */
  71017. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  71018. __extends(DepthOfFieldMergePostProcess, _super);
  71019. /**
  71020. * Creates a new instance of DepthOfFieldMergePostProcess
  71021. * @param name The name of the effect.
  71022. * @param originalFromInput Post process which's input will be used for the merge.
  71023. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  71024. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  71025. * @param options The required width/height ratio to downsize to before computing the render pass.
  71026. * @param camera The camera to apply the render pass to.
  71027. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71028. * @param engine The engine which the post process will be applied. (default: current engine)
  71029. * @param reusable If the post process can be reused on the same frame. (default: false)
  71030. * @param textureType Type of textures used when performing the post process. (default: 0)
  71031. * @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)
  71032. */
  71033. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71034. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71035. if (blockCompilation === void 0) { blockCompilation = false; }
  71036. var _this = _super.call(this, name, "depthOfFieldMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  71037. _this.blurSteps = blurSteps;
  71038. _this.onApplyObservable.add(function (effect) {
  71039. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  71040. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  71041. blurSteps.forEach(function (step, index) {
  71042. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  71043. });
  71044. });
  71045. if (!blockCompilation) {
  71046. _this.updateEffect();
  71047. }
  71048. return _this;
  71049. }
  71050. /**
  71051. * Updates the effect with the current post process compile time values and recompiles the shader.
  71052. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  71053. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  71054. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  71055. * @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
  71056. * @param onCompiled Called when the shader has been compiled.
  71057. * @param onError Called if there is an error when compiling a shader.
  71058. */
  71059. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  71060. if (defines === void 0) { defines = null; }
  71061. if (uniforms === void 0) { uniforms = null; }
  71062. if (samplers === void 0) { samplers = null; }
  71063. if (!defines) {
  71064. defines = "";
  71065. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  71066. }
  71067. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  71068. };
  71069. return DepthOfFieldMergePostProcess;
  71070. }(BABYLON.PostProcess));
  71071. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  71072. })(BABYLON || (BABYLON = {}));
  71073. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  71074. "use strict";
  71075. var BABYLON;
  71076. (function (BABYLON) {
  71077. /**
  71078. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  71079. */
  71080. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  71081. __extends(CircleOfConfusionPostProcess, _super);
  71082. /**
  71083. * Creates a new instance CircleOfConfusionPostProcess
  71084. * @param name The name of the effect.
  71085. * @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.
  71086. * @param options The required width/height ratio to downsize to before computing the render pass.
  71087. * @param camera The camera to apply the render pass to.
  71088. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71089. * @param engine The engine which the post process will be applied. (default: current engine)
  71090. * @param reusable If the post process can be reused on the same frame. (default: false)
  71091. * @param textureType Type of textures used when performing the post process. (default: 0)
  71092. * @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)
  71093. */
  71094. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71095. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71096. if (blockCompilation === void 0) { blockCompilation = false; }
  71097. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  71098. /**
  71099. * 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.
  71100. */
  71101. _this.lensSize = 50;
  71102. /**
  71103. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  71104. */
  71105. _this.fStop = 1.4;
  71106. /**
  71107. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  71108. */
  71109. _this.focusDistance = 2000;
  71110. /**
  71111. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  71112. */
  71113. _this.focalLength = 50;
  71114. _this._depthTexture = null;
  71115. _this._depthTexture = depthTexture;
  71116. _this.onApplyObservable.add(function (effect) {
  71117. if (!_this._depthTexture) {
  71118. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  71119. return;
  71120. }
  71121. effect.setTexture("depthSampler", _this._depthTexture);
  71122. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  71123. var aperture = _this.lensSize / _this.fStop;
  71124. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  71125. effect.setFloat('focusDistance', _this.focusDistance);
  71126. effect.setFloat('cocPrecalculation', cocPrecalculation);
  71127. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  71128. });
  71129. return _this;
  71130. }
  71131. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  71132. /**
  71133. * 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.
  71134. */
  71135. set: function (value) {
  71136. this._depthTexture = value;
  71137. },
  71138. enumerable: true,
  71139. configurable: true
  71140. });
  71141. return CircleOfConfusionPostProcess;
  71142. }(BABYLON.PostProcess));
  71143. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  71144. })(BABYLON || (BABYLON = {}));
  71145. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  71146. "use strict";
  71147. var BABYLON;
  71148. (function (BABYLON) {
  71149. /**
  71150. * Specifies the level of max blur that should be applied when using the depth of field effect
  71151. */
  71152. var DepthOfFieldEffectBlurLevel;
  71153. (function (DepthOfFieldEffectBlurLevel) {
  71154. /**
  71155. * Subtle blur
  71156. */
  71157. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  71158. /**
  71159. * Medium blur
  71160. */
  71161. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  71162. /**
  71163. * Large blur
  71164. */
  71165. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  71166. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  71167. ;
  71168. /**
  71169. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  71170. */
  71171. var DepthOfFieldEffect = /** @class */ (function (_super) {
  71172. __extends(DepthOfFieldEffect, _super);
  71173. /**
  71174. * Creates a new instance DepthOfFieldEffect
  71175. * @param scene The scene the effect belongs to.
  71176. * @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.
  71177. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  71178. * @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)
  71179. */
  71180. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  71181. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  71182. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  71183. if (blockCompilation === void 0) { blockCompilation = false; }
  71184. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  71185. return _this._effects;
  71186. }, true) || this;
  71187. /**
  71188. * Internal post processes in depth of field effect
  71189. */
  71190. _this._effects = [];
  71191. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  71192. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71193. // 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)
  71194. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  71195. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  71196. _this._depthOfFieldBlurY = [];
  71197. _this._depthOfFieldBlurX = [];
  71198. var blurCount = 1;
  71199. var kernelSize = 15;
  71200. switch (blurLevel) {
  71201. case DepthOfFieldEffectBlurLevel.High: {
  71202. blurCount = 3;
  71203. kernelSize = 51;
  71204. break;
  71205. }
  71206. case DepthOfFieldEffectBlurLevel.Medium: {
  71207. blurCount = 2;
  71208. kernelSize = 31;
  71209. break;
  71210. }
  71211. default: {
  71212. kernelSize = 15;
  71213. blurCount = 1;
  71214. break;
  71215. }
  71216. }
  71217. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  71218. for (var i = 0; i < blurCount; i++) {
  71219. 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);
  71220. blurY.autoClear = false;
  71221. 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);
  71222. blurX.autoClear = false;
  71223. _this._depthOfFieldBlurY.push(blurY);
  71224. _this._depthOfFieldBlurX.push(blurX);
  71225. }
  71226. // Set all post processes on the effect.
  71227. _this._effects = [_this._circleOfConfusion];
  71228. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  71229. _this._effects.push(_this._depthOfFieldBlurY[i]);
  71230. _this._effects.push(_this._depthOfFieldBlurX[i]);
  71231. }
  71232. // Merge blurred images with original image based on circleOfConfusion
  71233. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71234. _this._dofMerge.autoClear = false;
  71235. _this._effects.push(_this._dofMerge);
  71236. return _this;
  71237. }
  71238. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  71239. get: function () {
  71240. return this._circleOfConfusion.focalLength;
  71241. },
  71242. /**
  71243. * The focal the length of the camera used in the effect
  71244. */
  71245. set: function (value) {
  71246. this._circleOfConfusion.focalLength = value;
  71247. },
  71248. enumerable: true,
  71249. configurable: true
  71250. });
  71251. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  71252. get: function () {
  71253. return this._circleOfConfusion.fStop;
  71254. },
  71255. /**
  71256. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  71257. */
  71258. set: function (value) {
  71259. this._circleOfConfusion.fStop = value;
  71260. },
  71261. enumerable: true,
  71262. configurable: true
  71263. });
  71264. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  71265. get: function () {
  71266. return this._circleOfConfusion.focusDistance;
  71267. },
  71268. /**
  71269. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  71270. */
  71271. set: function (value) {
  71272. this._circleOfConfusion.focusDistance = value;
  71273. },
  71274. enumerable: true,
  71275. configurable: true
  71276. });
  71277. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  71278. get: function () {
  71279. return this._circleOfConfusion.lensSize;
  71280. },
  71281. /**
  71282. * 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.
  71283. */
  71284. set: function (value) {
  71285. this._circleOfConfusion.lensSize = value;
  71286. },
  71287. enumerable: true,
  71288. configurable: true
  71289. });
  71290. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  71291. /**
  71292. * 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.
  71293. */
  71294. set: function (value) {
  71295. this._circleOfConfusion.depthTexture = value;
  71296. },
  71297. enumerable: true,
  71298. configurable: true
  71299. });
  71300. /**
  71301. * Disposes each of the internal effects for a given camera.
  71302. * @param camera The camera to dispose the effect on.
  71303. */
  71304. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  71305. for (var effect in this._effects) {
  71306. this._effects[effect].dispose(camera);
  71307. }
  71308. };
  71309. /**
  71310. * Internal
  71311. */
  71312. DepthOfFieldEffect.prototype._updateEffects = function () {
  71313. for (var effect in this._effects) {
  71314. this._effects[effect].updateEffect();
  71315. }
  71316. };
  71317. /**
  71318. * Internal
  71319. * @returns if all the contained post processes are ready.
  71320. */
  71321. DepthOfFieldEffect.prototype._isReady = function () {
  71322. for (var effect in this._effects) {
  71323. if (!this._effects[effect].isReady()) {
  71324. return false;
  71325. }
  71326. }
  71327. return true;
  71328. };
  71329. return DepthOfFieldEffect;
  71330. }(BABYLON.PostProcessRenderEffect));
  71331. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  71332. })(BABYLON || (BABYLON = {}));
  71333. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  71334. "use strict";
  71335. var BABYLON;
  71336. (function (BABYLON) {
  71337. /**
  71338. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  71339. */
  71340. var BloomMergePostProcess = /** @class */ (function (_super) {
  71341. __extends(BloomMergePostProcess, _super);
  71342. /**
  71343. * Creates a new instance of @see BloomMergePostProcess
  71344. * @param name The name of the effect.
  71345. * @param originalFromInput Post process which's input will be used for the merge.
  71346. * @param blurred Blurred highlights post process which's output will be used.
  71347. * @param weight Weight of the bloom to be added to the original input.
  71348. * @param options The required width/height ratio to downsize to before computing the render pass.
  71349. * @param camera The camera to apply the render pass to.
  71350. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71351. * @param engine The engine which the post process will be applied. (default: current engine)
  71352. * @param reusable If the post process can be reused on the same frame. (default: false)
  71353. * @param textureType Type of textures used when performing the post process. (default: 0)
  71354. * @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)
  71355. */
  71356. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71357. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71358. if (blockCompilation === void 0) { blockCompilation = false; }
  71359. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  71360. _this.weight = weight;
  71361. _this.onApplyObservable.add(function (effect) {
  71362. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  71363. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  71364. effect.setFloat("bloomWeight", _this.weight);
  71365. });
  71366. if (!blockCompilation) {
  71367. _this.updateEffect();
  71368. }
  71369. return _this;
  71370. }
  71371. return BloomMergePostProcess;
  71372. }(BABYLON.PostProcess));
  71373. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  71374. })(BABYLON || (BABYLON = {}));
  71375. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  71376. "use strict";
  71377. var BABYLON;
  71378. (function (BABYLON) {
  71379. /**
  71380. * 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.
  71381. */
  71382. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  71383. __extends(ExtractHighlightsPostProcess, _super);
  71384. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  71385. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71386. if (blockCompilation === void 0) { blockCompilation = false; }
  71387. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  71388. /**
  71389. * The luminance threshold, pixels below this value will be set to black.
  71390. */
  71391. _this.threshold = 0.9;
  71392. /**
  71393. * Internal
  71394. */
  71395. _this._exposure = 1;
  71396. /**
  71397. * Post process which has the input texture to be used when performing highlight extraction
  71398. */
  71399. _this._inputPostProcess = null;
  71400. _this.onApplyObservable.add(function (effect) {
  71401. if (_this._inputPostProcess) {
  71402. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  71403. }
  71404. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  71405. effect.setFloat('exposure', _this._exposure);
  71406. });
  71407. return _this;
  71408. }
  71409. return ExtractHighlightsPostProcess;
  71410. }(BABYLON.PostProcess));
  71411. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  71412. })(BABYLON || (BABYLON = {}));
  71413. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  71414. "use strict";
  71415. var BABYLON;
  71416. (function (BABYLON) {
  71417. /**
  71418. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  71419. */
  71420. var BloomEffect = /** @class */ (function (_super) {
  71421. __extends(BloomEffect, _super);
  71422. /**
  71423. * Creates a new instance of @see BloomEffect
  71424. * @param scene The scene the effect belongs to.
  71425. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  71426. * @param bloomKernel The size of the kernel to be used when applying the blur.
  71427. * @param bloomWeight The the strength of bloom.
  71428. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  71429. * @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)
  71430. */
  71431. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  71432. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  71433. if (blockCompilation === void 0) { blockCompilation = false; }
  71434. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  71435. return _this._effects;
  71436. }, true) || this;
  71437. _this.bloomScale = bloomScale;
  71438. /**
  71439. * Internal
  71440. */
  71441. _this._effects = [];
  71442. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71443. _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);
  71444. _this._blurX.alwaysForcePOT = true;
  71445. _this._blurX.autoClear = false;
  71446. _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);
  71447. _this._blurY.alwaysForcePOT = true;
  71448. _this._blurY.autoClear = false;
  71449. _this.kernel = bloomKernel;
  71450. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  71451. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  71452. _this._merge.autoClear = false;
  71453. _this._effects.push(_this._merge);
  71454. return _this;
  71455. }
  71456. Object.defineProperty(BloomEffect.prototype, "threshold", {
  71457. /**
  71458. * The luminance threshold to find bright areas of the image to bloom.
  71459. */
  71460. get: function () {
  71461. return this._downscale.threshold;
  71462. },
  71463. set: function (value) {
  71464. this._downscale.threshold = value;
  71465. },
  71466. enumerable: true,
  71467. configurable: true
  71468. });
  71469. Object.defineProperty(BloomEffect.prototype, "weight", {
  71470. /**
  71471. * The strength of the bloom.
  71472. */
  71473. get: function () {
  71474. return this._merge.weight;
  71475. },
  71476. set: function (value) {
  71477. this._merge.weight = value;
  71478. },
  71479. enumerable: true,
  71480. configurable: true
  71481. });
  71482. Object.defineProperty(BloomEffect.prototype, "kernel", {
  71483. /**
  71484. * Specifies the size of the bloom blur kernel, relative to the final output size
  71485. */
  71486. get: function () {
  71487. return this._blurX.kernel / this.bloomScale;
  71488. },
  71489. set: function (value) {
  71490. this._blurX.kernel = value * this.bloomScale;
  71491. this._blurY.kernel = value * this.bloomScale;
  71492. },
  71493. enumerable: true,
  71494. configurable: true
  71495. });
  71496. /**
  71497. * Disposes each of the internal effects for a given camera.
  71498. * @param camera The camera to dispose the effect on.
  71499. */
  71500. BloomEffect.prototype.disposeEffects = function (camera) {
  71501. for (var effect in this._effects) {
  71502. this._effects[effect].dispose(camera);
  71503. }
  71504. };
  71505. /**
  71506. * Internal
  71507. */
  71508. BloomEffect.prototype._updateEffects = function () {
  71509. for (var effect in this._effects) {
  71510. this._effects[effect].updateEffect();
  71511. }
  71512. };
  71513. /**
  71514. * Internal
  71515. * @returns if all the contained post processes are ready.
  71516. */
  71517. BloomEffect.prototype._isReady = function () {
  71518. for (var effect in this._effects) {
  71519. if (!this._effects[effect].isReady()) {
  71520. return false;
  71521. }
  71522. }
  71523. return true;
  71524. };
  71525. return BloomEffect;
  71526. }(BABYLON.PostProcessRenderEffect));
  71527. BABYLON.BloomEffect = BloomEffect;
  71528. })(BABYLON || (BABYLON = {}));
  71529. //# sourceMappingURL=babylon.bloomEffect.js.map
  71530. "use strict";
  71531. var BABYLON;
  71532. (function (BABYLON) {
  71533. /**
  71534. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  71535. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  71536. */
  71537. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  71538. __extends(DefaultRenderingPipeline, _super);
  71539. /**
  71540. * @constructor
  71541. * @param {string} name - The rendering pipeline name
  71542. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  71543. * @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)
  71544. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  71545. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  71546. */
  71547. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  71548. if (automaticBuild === void 0) { automaticBuild = true; }
  71549. var _this = _super.call(this, scene.getEngine(), name) || this;
  71550. _this._originalCameras = [];
  71551. /**
  71552. * ID of the sharpen post process,
  71553. */
  71554. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  71555. /**
  71556. * ID of the image processing post process;
  71557. */
  71558. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  71559. /**
  71560. * ID of the Fast Approximate Anti-Aliasing post process;
  71561. */
  71562. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  71563. /**
  71564. * ID of the chromatic aberration post process,
  71565. */
  71566. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  71567. /**
  71568. * ID of the grain post process
  71569. */
  71570. _this.GrainPostProcessId = "GrainPostProcessEffect";
  71571. /**
  71572. * Animations which can be used to tweak settings over a period of time
  71573. */
  71574. _this.animations = [];
  71575. _this._imageProcessingConfigurationObserver = null;
  71576. // Values
  71577. _this._sharpenEnabled = false;
  71578. _this._bloomEnabled = false;
  71579. _this._depthOfFieldEnabled = false;
  71580. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  71581. _this._fxaaEnabled = false;
  71582. _this._imageProcessingEnabled = true;
  71583. _this._bloomScale = 0.5;
  71584. _this._chromaticAberrationEnabled = false;
  71585. _this._grainEnabled = false;
  71586. _this._buildAllowed = true;
  71587. _this._resizeObserver = null;
  71588. _this._hardwareScaleLevel = 1.0;
  71589. _this._bloomKernel = 64;
  71590. /**
  71591. * Specifies the weight of the bloom in the final rendering
  71592. */
  71593. _this._bloomWeight = 0.15;
  71594. /**
  71595. * Specifies the luma threshold for the area that will be blurred by the bloom
  71596. */
  71597. _this._bloomThreshold = 0.9;
  71598. _this._samples = 1;
  71599. _this._hasCleared = false;
  71600. _this._prevPostProcess = null;
  71601. _this._prevPrevPostProcess = null;
  71602. _this._cameras = cameras || [];
  71603. _this._originalCameras = _this._cameras.slice();
  71604. _this._buildAllowed = automaticBuild;
  71605. // Initialize
  71606. _this._scene = scene;
  71607. var caps = _this._scene.getEngine().getCaps();
  71608. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  71609. // Misc
  71610. if (_this._hdr) {
  71611. if (caps.textureHalfFloatRender) {
  71612. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  71613. }
  71614. else if (caps.textureFloatRender) {
  71615. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71616. }
  71617. }
  71618. else {
  71619. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71620. }
  71621. // Attach
  71622. scene.postProcessRenderPipelineManager.addPipeline(_this);
  71623. var engine = _this._scene.getEngine();
  71624. // Create post processes before hand so they can be modified before enabled.
  71625. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  71626. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  71627. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  71628. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  71629. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  71630. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  71631. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  71632. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  71633. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  71634. _this._resizeObserver = engine.onResizeObservable.add(function () {
  71635. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  71636. _this.bloomKernel = _this.bloomKernel;
  71637. });
  71638. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  71639. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  71640. });
  71641. _this._buildPipeline();
  71642. return _this;
  71643. }
  71644. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  71645. get: function () {
  71646. return this._sharpenEnabled;
  71647. },
  71648. /**
  71649. * Enable or disable the sharpen process from the pipeline
  71650. */
  71651. set: function (enabled) {
  71652. if (this._sharpenEnabled === enabled) {
  71653. return;
  71654. }
  71655. this._sharpenEnabled = enabled;
  71656. this._buildPipeline();
  71657. },
  71658. enumerable: true,
  71659. configurable: true
  71660. });
  71661. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  71662. /**
  71663. * Specifies the size of the bloom blur kernel, relative to the final output size
  71664. */
  71665. get: function () {
  71666. return this._bloomKernel;
  71667. },
  71668. set: function (value) {
  71669. this._bloomKernel = value;
  71670. this.bloom.kernel = value / this._hardwareScaleLevel;
  71671. },
  71672. enumerable: true,
  71673. configurable: true
  71674. });
  71675. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  71676. get: function () {
  71677. return this._bloomWeight;
  71678. },
  71679. /**
  71680. * The strength of the bloom.
  71681. */
  71682. set: function (value) {
  71683. if (this._bloomWeight === value) {
  71684. return;
  71685. }
  71686. this.bloom.weight = value;
  71687. this._bloomWeight = value;
  71688. },
  71689. enumerable: true,
  71690. configurable: true
  71691. });
  71692. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  71693. get: function () {
  71694. return this._bloomThreshold;
  71695. },
  71696. /**
  71697. * The strength of the bloom.
  71698. */
  71699. set: function (value) {
  71700. if (this._bloomThreshold === value) {
  71701. return;
  71702. }
  71703. this.bloom.threshold = value;
  71704. this._bloomThreshold = value;
  71705. },
  71706. enumerable: true,
  71707. configurable: true
  71708. });
  71709. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  71710. get: function () {
  71711. return this._bloomScale;
  71712. },
  71713. /**
  71714. * The scale of the bloom, lower value will provide better performance.
  71715. */
  71716. set: function (value) {
  71717. if (this._bloomScale === value) {
  71718. return;
  71719. }
  71720. this._bloomScale = value;
  71721. // recreate bloom and dispose old as this setting is not dynamic
  71722. this._rebuildBloom();
  71723. this._buildPipeline();
  71724. },
  71725. enumerable: true,
  71726. configurable: true
  71727. });
  71728. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  71729. get: function () {
  71730. return this._bloomEnabled;
  71731. },
  71732. /**
  71733. * Enable or disable the bloom from the pipeline
  71734. */
  71735. set: function (enabled) {
  71736. if (this._bloomEnabled === enabled) {
  71737. return;
  71738. }
  71739. this._bloomEnabled = enabled;
  71740. this._buildPipeline();
  71741. },
  71742. enumerable: true,
  71743. configurable: true
  71744. });
  71745. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  71746. // recreate bloom and dispose old as this setting is not dynamic
  71747. var oldBloom = this.bloom;
  71748. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  71749. this.bloom.threshold = oldBloom.threshold;
  71750. for (var i = 0; i < this._cameras.length; i++) {
  71751. oldBloom.disposeEffects(this._cameras[i]);
  71752. }
  71753. };
  71754. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  71755. /**
  71756. * If the depth of field is enabled.
  71757. */
  71758. get: function () {
  71759. return this._depthOfFieldEnabled;
  71760. },
  71761. set: function (enabled) {
  71762. if (this._depthOfFieldEnabled === enabled) {
  71763. return;
  71764. }
  71765. this._depthOfFieldEnabled = enabled;
  71766. this._buildPipeline();
  71767. },
  71768. enumerable: true,
  71769. configurable: true
  71770. });
  71771. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  71772. /**
  71773. * Blur level of the depth of field effect. (Higher blur will effect performance)
  71774. */
  71775. get: function () {
  71776. return this._depthOfFieldBlurLevel;
  71777. },
  71778. set: function (value) {
  71779. if (this._depthOfFieldBlurLevel === value) {
  71780. return;
  71781. }
  71782. this._depthOfFieldBlurLevel = value;
  71783. // recreate dof and dispose old as this setting is not dynamic
  71784. var oldDof = this.depthOfField;
  71785. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  71786. this.depthOfField.focalLength = oldDof.focalLength;
  71787. this.depthOfField.focusDistance = oldDof.focusDistance;
  71788. this.depthOfField.fStop = oldDof.fStop;
  71789. this.depthOfField.lensSize = oldDof.lensSize;
  71790. for (var i = 0; i < this._cameras.length; i++) {
  71791. oldDof.disposeEffects(this._cameras[i]);
  71792. }
  71793. this._buildPipeline();
  71794. },
  71795. enumerable: true,
  71796. configurable: true
  71797. });
  71798. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  71799. get: function () {
  71800. return this._fxaaEnabled;
  71801. },
  71802. /**
  71803. * If the anti aliasing is enabled.
  71804. */
  71805. set: function (enabled) {
  71806. if (this._fxaaEnabled === enabled) {
  71807. return;
  71808. }
  71809. this._fxaaEnabled = enabled;
  71810. this._buildPipeline();
  71811. },
  71812. enumerable: true,
  71813. configurable: true
  71814. });
  71815. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  71816. get: function () {
  71817. return this._samples;
  71818. },
  71819. /**
  71820. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  71821. */
  71822. set: function (sampleCount) {
  71823. if (this._samples === sampleCount) {
  71824. return;
  71825. }
  71826. this._samples = sampleCount;
  71827. this._buildPipeline();
  71828. },
  71829. enumerable: true,
  71830. configurable: true
  71831. });
  71832. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  71833. get: function () {
  71834. return this._imageProcessingEnabled;
  71835. },
  71836. /**
  71837. * If image processing is enabled.
  71838. */
  71839. set: function (enabled) {
  71840. if (this._imageProcessingEnabled === enabled) {
  71841. return;
  71842. }
  71843. this._imageProcessingEnabled = enabled;
  71844. this._buildPipeline();
  71845. },
  71846. enumerable: true,
  71847. configurable: true
  71848. });
  71849. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  71850. get: function () {
  71851. return this._chromaticAberrationEnabled;
  71852. },
  71853. /**
  71854. * Enable or disable the chromaticAberration process from the pipeline
  71855. */
  71856. set: function (enabled) {
  71857. if (this._chromaticAberrationEnabled === enabled) {
  71858. return;
  71859. }
  71860. this._chromaticAberrationEnabled = enabled;
  71861. this._buildPipeline();
  71862. },
  71863. enumerable: true,
  71864. configurable: true
  71865. });
  71866. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  71867. get: function () {
  71868. return this._grainEnabled;
  71869. },
  71870. /**
  71871. * Enable or disable the grain process from the pipeline
  71872. */
  71873. set: function (enabled) {
  71874. if (this._grainEnabled === enabled) {
  71875. return;
  71876. }
  71877. this._grainEnabled = enabled;
  71878. this._buildPipeline();
  71879. },
  71880. enumerable: true,
  71881. configurable: true
  71882. });
  71883. /**
  71884. * Force the compilation of the entire pipeline.
  71885. */
  71886. DefaultRenderingPipeline.prototype.prepare = function () {
  71887. var previousState = this._buildAllowed;
  71888. this._buildAllowed = true;
  71889. this._buildPipeline();
  71890. this._buildAllowed = previousState;
  71891. };
  71892. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  71893. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  71894. if (this._hasCleared) {
  71895. postProcess.autoClear = false;
  71896. }
  71897. else {
  71898. postProcess.autoClear = true;
  71899. this._scene.autoClear = false;
  71900. this._hasCleared = true;
  71901. }
  71902. if (!skipTextureSharing) {
  71903. if (this._prevPrevPostProcess) {
  71904. postProcess.shareOutputWith(this._prevPrevPostProcess);
  71905. }
  71906. else {
  71907. postProcess.useOwnOutput();
  71908. }
  71909. if (this._prevPostProcess) {
  71910. this._prevPrevPostProcess = this._prevPostProcess;
  71911. }
  71912. this._prevPostProcess = postProcess;
  71913. }
  71914. };
  71915. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  71916. var _this = this;
  71917. if (!this._buildAllowed) {
  71918. return;
  71919. }
  71920. this._scene.autoClear = true;
  71921. var engine = this._scene.getEngine();
  71922. this._disposePostProcesses();
  71923. if (this._cameras !== null) {
  71924. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71925. // get back cameras to be used to reattach pipeline
  71926. this._cameras = this._originalCameras.slice();
  71927. }
  71928. this._reset();
  71929. this._prevPostProcess = null;
  71930. this._prevPrevPostProcess = null;
  71931. this._hasCleared = false;
  71932. if (this.depthOfFieldEnabled) {
  71933. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  71934. this.depthOfField.depthTexture = depthTexture;
  71935. if (!this.depthOfField._isReady()) {
  71936. this.depthOfField._updateEffects();
  71937. }
  71938. this.addEffect(this.depthOfField);
  71939. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  71940. }
  71941. if (this.bloomEnabled) {
  71942. if (!this.bloom._isReady()) {
  71943. this.bloom._updateEffects();
  71944. }
  71945. this.addEffect(this.bloom);
  71946. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  71947. }
  71948. if (this._imageProcessingEnabled) {
  71949. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71950. if (this._hdr) {
  71951. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71952. this._setAutoClearAndTextureSharing(this.imageProcessing);
  71953. }
  71954. else {
  71955. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71956. }
  71957. }
  71958. if (this.sharpenEnabled) {
  71959. if (!this.sharpen.isReady()) {
  71960. this.sharpen.updateEffect();
  71961. }
  71962. this.addEffect(this._sharpenEffect);
  71963. this._setAutoClearAndTextureSharing(this.sharpen);
  71964. }
  71965. if (this.grainEnabled) {
  71966. if (!this.grain.isReady()) {
  71967. this.grain.updateEffect();
  71968. }
  71969. this.addEffect(this._grainEffect);
  71970. this._setAutoClearAndTextureSharing(this.grain);
  71971. }
  71972. if (this.chromaticAberrationEnabled) {
  71973. if (!this.chromaticAberration.isReady()) {
  71974. this.chromaticAberration.updateEffect();
  71975. }
  71976. this.addEffect(this._chromaticAberrationEffect);
  71977. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71978. }
  71979. if (this.fxaaEnabled) {
  71980. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71981. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71982. this._setAutoClearAndTextureSharing(this.fxaa, true);
  71983. }
  71984. if (this._cameras !== null) {
  71985. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71986. }
  71987. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  71988. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71989. }
  71990. };
  71991. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71992. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71993. for (var i = 0; i < this._cameras.length; i++) {
  71994. var camera = this._cameras[i];
  71995. if (this.imageProcessing) {
  71996. this.imageProcessing.dispose(camera);
  71997. }
  71998. if (this.fxaa) {
  71999. this.fxaa.dispose(camera);
  72000. }
  72001. // These are created in the constructor and should not be disposed on every pipeline change
  72002. if (disposeNonRecreated) {
  72003. if (this.sharpen) {
  72004. this.sharpen.dispose(camera);
  72005. }
  72006. if (this.depthOfField) {
  72007. this.depthOfField.disposeEffects(camera);
  72008. }
  72009. if (this.bloom) {
  72010. this.bloom.disposeEffects(camera);
  72011. }
  72012. if (this.chromaticAberration) {
  72013. this.chromaticAberration.dispose(camera);
  72014. }
  72015. if (this.grain) {
  72016. this.grain.dispose(camera);
  72017. }
  72018. }
  72019. }
  72020. this.imageProcessing = null;
  72021. this.fxaa = null;
  72022. if (disposeNonRecreated) {
  72023. this.sharpen = null;
  72024. this._sharpenEffect = null;
  72025. this.depthOfField = null;
  72026. this.bloom = null;
  72027. this.chromaticAberration = null;
  72028. this._chromaticAberrationEffect = null;
  72029. this.grain = null;
  72030. this._grainEffect = null;
  72031. }
  72032. };
  72033. /**
  72034. * Dispose of the pipeline and stop all post processes
  72035. */
  72036. DefaultRenderingPipeline.prototype.dispose = function () {
  72037. this._disposePostProcesses(true);
  72038. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  72039. this._scene.autoClear = true;
  72040. if (this._resizeObserver) {
  72041. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  72042. this._resizeObserver = null;
  72043. }
  72044. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  72045. _super.prototype.dispose.call(this);
  72046. };
  72047. /**
  72048. * Serialize the rendering pipeline (Used when exporting)
  72049. * @returns the serialized object
  72050. */
  72051. DefaultRenderingPipeline.prototype.serialize = function () {
  72052. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  72053. serializationObject.customType = "DefaultRenderingPipeline";
  72054. return serializationObject;
  72055. };
  72056. /**
  72057. * Parse the serialized pipeline
  72058. * @param source Source pipeline.
  72059. * @param scene The scene to load the pipeline to.
  72060. * @param rootUrl The URL of the serialized pipeline.
  72061. * @returns An instantiated pipeline from the serialized object.
  72062. */
  72063. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  72064. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  72065. };
  72066. __decorate([
  72067. BABYLON.serialize()
  72068. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  72069. __decorate([
  72070. BABYLON.serialize()
  72071. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  72072. __decorate([
  72073. BABYLON.serialize()
  72074. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  72075. __decorate([
  72076. BABYLON.serialize()
  72077. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  72078. __decorate([
  72079. BABYLON.serialize()
  72080. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  72081. __decorate([
  72082. BABYLON.serialize()
  72083. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  72084. __decorate([
  72085. BABYLON.serialize()
  72086. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  72087. __decorate([
  72088. BABYLON.serialize()
  72089. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  72090. __decorate([
  72091. BABYLON.serialize()
  72092. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  72093. __decorate([
  72094. BABYLON.serialize()
  72095. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  72096. __decorate([
  72097. BABYLON.serialize()
  72098. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  72099. __decorate([
  72100. BABYLON.serialize()
  72101. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  72102. __decorate([
  72103. BABYLON.serialize()
  72104. ], DefaultRenderingPipeline.prototype, "samples", null);
  72105. __decorate([
  72106. BABYLON.serialize()
  72107. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  72108. __decorate([
  72109. BABYLON.serialize()
  72110. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  72111. __decorate([
  72112. BABYLON.serialize()
  72113. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  72114. return DefaultRenderingPipeline;
  72115. }(BABYLON.PostProcessRenderPipeline));
  72116. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  72117. })(BABYLON || (BABYLON = {}));
  72118. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  72119. "use strict";
  72120. var BABYLON;
  72121. (function (BABYLON) {
  72122. /**
  72123. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  72124. */
  72125. var GeometryBufferRenderer = /** @class */ (function () {
  72126. /**
  72127. * Creates a new G Buffer for the scene
  72128. * @param scene The scene the buffer belongs to
  72129. * @param ratio How big is the buffer related to the main canvas.
  72130. */
  72131. function GeometryBufferRenderer(scene, ratio) {
  72132. if (ratio === void 0) { ratio = 1; }
  72133. this._enablePosition = false;
  72134. this._scene = scene;
  72135. this._ratio = ratio;
  72136. // Render target
  72137. this._createRenderTargets();
  72138. }
  72139. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  72140. /**
  72141. * Set the render list (meshes to be rendered) used in the G buffer.
  72142. */
  72143. set: function (meshes) {
  72144. this._multiRenderTarget.renderList = meshes;
  72145. },
  72146. enumerable: true,
  72147. configurable: true
  72148. });
  72149. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  72150. /**
  72151. * Gets wether or not G buffer are supported by the running hardware.
  72152. * This requires draw buffer supports
  72153. */
  72154. get: function () {
  72155. return this._multiRenderTarget.isSupported;
  72156. },
  72157. enumerable: true,
  72158. configurable: true
  72159. });
  72160. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  72161. /**
  72162. * Gets wether or not position are enabled for the G buffer.
  72163. */
  72164. get: function () {
  72165. return this._enablePosition;
  72166. },
  72167. /**
  72168. * Sets wether or not position are enabled for the G buffer.
  72169. */
  72170. set: function (enable) {
  72171. this._enablePosition = enable;
  72172. this.dispose();
  72173. this._createRenderTargets();
  72174. },
  72175. enumerable: true,
  72176. configurable: true
  72177. });
  72178. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  72179. /**
  72180. * Gets the scene associated with the buffer.
  72181. */
  72182. get: function () {
  72183. return this._scene;
  72184. },
  72185. enumerable: true,
  72186. configurable: true
  72187. });
  72188. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  72189. /**
  72190. * Gets the ratio used by the buffer during its creation.
  72191. * How big is the buffer related to the main canvas.
  72192. */
  72193. get: function () {
  72194. return this._ratio;
  72195. },
  72196. enumerable: true,
  72197. configurable: true
  72198. });
  72199. /**
  72200. * Checks wether everything is ready to render a submesh to the G buffer.
  72201. * @param subMesh the submesh to check readiness for
  72202. * @param useInstances is the mesh drawn using instance or not
  72203. * @returns true if ready otherwise false
  72204. */
  72205. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  72206. var material = subMesh.getMaterial();
  72207. if (material && material.disableDepthWrite) {
  72208. return false;
  72209. }
  72210. var defines = [];
  72211. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  72212. var mesh = subMesh.getMesh();
  72213. // Alpha test
  72214. if (material && material.needAlphaTesting()) {
  72215. defines.push("#define ALPHATEST");
  72216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72217. attribs.push(BABYLON.VertexBuffer.UVKind);
  72218. defines.push("#define UV1");
  72219. }
  72220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72221. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72222. defines.push("#define UV2");
  72223. }
  72224. }
  72225. // Buffers
  72226. if (this._enablePosition) {
  72227. defines.push("#define POSITION");
  72228. }
  72229. // Bones
  72230. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72231. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72232. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72233. if (mesh.numBoneInfluencers > 4) {
  72234. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72235. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72236. }
  72237. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72238. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72239. }
  72240. else {
  72241. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72242. }
  72243. // Instances
  72244. if (useInstances) {
  72245. defines.push("#define INSTANCES");
  72246. attribs.push("world0");
  72247. attribs.push("world1");
  72248. attribs.push("world2");
  72249. attribs.push("world3");
  72250. }
  72251. // Get correct effect
  72252. var join = defines.join("\n");
  72253. if (this._cachedDefines !== join) {
  72254. this._cachedDefines = join;
  72255. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  72256. }
  72257. return this._effect.isReady();
  72258. };
  72259. /**
  72260. * Gets the current underlying G Buffer.
  72261. * @returns the buffer
  72262. */
  72263. GeometryBufferRenderer.prototype.getGBuffer = function () {
  72264. return this._multiRenderTarget;
  72265. };
  72266. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  72267. /**
  72268. * Gets the number of samples used to render the buffer (anti aliasing).
  72269. */
  72270. get: function () {
  72271. return this._multiRenderTarget.samples;
  72272. },
  72273. /**
  72274. * Sets the number of samples used to render the buffer (anti aliasing).
  72275. */
  72276. set: function (value) {
  72277. this._multiRenderTarget.samples = value;
  72278. },
  72279. enumerable: true,
  72280. configurable: true
  72281. });
  72282. /**
  72283. * Disposes the renderer and frees up associated resources.
  72284. */
  72285. GeometryBufferRenderer.prototype.dispose = function () {
  72286. this.getGBuffer().dispose();
  72287. };
  72288. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  72289. var _this = this;
  72290. var engine = this._scene.getEngine();
  72291. var count = this._enablePosition ? 3 : 2;
  72292. 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 });
  72293. if (!this.isSupported) {
  72294. return;
  72295. }
  72296. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72297. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72298. this._multiRenderTarget.refreshRate = 1;
  72299. this._multiRenderTarget.renderParticles = false;
  72300. this._multiRenderTarget.renderList = null;
  72301. // set default depth value to 1.0 (far away)
  72302. this._multiRenderTarget.onClearObservable.add(function (engine) {
  72303. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  72304. });
  72305. // Custom render function
  72306. var renderSubMesh = function (subMesh) {
  72307. var mesh = subMesh.getRenderingMesh();
  72308. var scene = _this._scene;
  72309. var engine = scene.getEngine();
  72310. var material = subMesh.getMaterial();
  72311. if (!material) {
  72312. return;
  72313. }
  72314. // Culling
  72315. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72316. // Managing instances
  72317. var batch = mesh._getInstancesRenderList(subMesh._id);
  72318. if (batch.mustReturn) {
  72319. return;
  72320. }
  72321. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72322. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  72323. engine.enableEffect(_this._effect);
  72324. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72325. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72326. _this._effect.setMatrix("view", scene.getViewMatrix());
  72327. // Alpha test
  72328. if (material && material.needAlphaTesting()) {
  72329. var alphaTexture = material.getAlphaTestTexture();
  72330. if (alphaTexture) {
  72331. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72332. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72333. }
  72334. }
  72335. // Bones
  72336. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72337. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72338. }
  72339. // Draw
  72340. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72341. }
  72342. };
  72343. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72344. var index;
  72345. if (depthOnlySubMeshes.length) {
  72346. engine.setColorWrite(false);
  72347. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72348. renderSubMesh(depthOnlySubMeshes.data[index]);
  72349. }
  72350. engine.setColorWrite(true);
  72351. }
  72352. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72353. renderSubMesh(opaqueSubMeshes.data[index]);
  72354. }
  72355. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72356. renderSubMesh(alphaTestSubMeshes.data[index]);
  72357. }
  72358. };
  72359. };
  72360. return GeometryBufferRenderer;
  72361. }());
  72362. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  72363. })(BABYLON || (BABYLON = {}));
  72364. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  72365. "use strict";
  72366. var BABYLON;
  72367. (function (BABYLON) {
  72368. var RefractionPostProcess = /** @class */ (function (_super) {
  72369. __extends(RefractionPostProcess, _super);
  72370. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  72371. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  72372. _this.color = color;
  72373. _this.depth = depth;
  72374. _this.colorLevel = colorLevel;
  72375. _this._ownRefractionTexture = true;
  72376. _this.onActivateObservable.add(function (cam) {
  72377. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  72378. });
  72379. _this.onApplyObservable.add(function (effect) {
  72380. effect.setColor3("baseColor", _this.color);
  72381. effect.setFloat("depth", _this.depth);
  72382. effect.setFloat("colorLevel", _this.colorLevel);
  72383. effect.setTexture("refractionSampler", _this._refTexture);
  72384. });
  72385. return _this;
  72386. }
  72387. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  72388. /**
  72389. * Gets or sets the refraction texture
  72390. * Please note that you are responsible for disposing the texture if you set it manually
  72391. */
  72392. get: function () {
  72393. return this._refTexture;
  72394. },
  72395. set: function (value) {
  72396. if (this._refTexture && this._ownRefractionTexture) {
  72397. this._refTexture.dispose();
  72398. }
  72399. this._refTexture = value;
  72400. this._ownRefractionTexture = false;
  72401. },
  72402. enumerable: true,
  72403. configurable: true
  72404. });
  72405. // Methods
  72406. RefractionPostProcess.prototype.dispose = function (camera) {
  72407. if (this._refTexture && this._ownRefractionTexture) {
  72408. this._refTexture.dispose();
  72409. this._refTexture = null;
  72410. }
  72411. _super.prototype.dispose.call(this, camera);
  72412. };
  72413. return RefractionPostProcess;
  72414. }(BABYLON.PostProcess));
  72415. BABYLON.RefractionPostProcess = RefractionPostProcess;
  72416. })(BABYLON || (BABYLON = {}));
  72417. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  72418. "use strict";
  72419. var BABYLON;
  72420. (function (BABYLON) {
  72421. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  72422. __extends(BlackAndWhitePostProcess, _super);
  72423. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  72424. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  72425. _this.degree = 1;
  72426. _this.onApplyObservable.add(function (effect) {
  72427. effect.setFloat("degree", _this.degree);
  72428. });
  72429. return _this;
  72430. }
  72431. return BlackAndWhitePostProcess;
  72432. }(BABYLON.PostProcess));
  72433. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  72434. })(BABYLON || (BABYLON = {}));
  72435. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  72436. "use strict";
  72437. var BABYLON;
  72438. (function (BABYLON) {
  72439. /**
  72440. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  72441. * input texture to perform effects such as edge detection or sharpening
  72442. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  72443. */
  72444. var ConvolutionPostProcess = /** @class */ (function (_super) {
  72445. __extends(ConvolutionPostProcess, _super);
  72446. /**
  72447. * Creates a new instance ConvolutionPostProcess
  72448. * @param name The name of the effect.
  72449. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  72450. * @param options The required width/height ratio to downsize to before computing the render pass.
  72451. * @param camera The camera to apply the render pass to.
  72452. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  72453. * @param engine The engine which the post process will be applied. (default: current engine)
  72454. * @param reusable If the post process can be reused on the same frame. (default: false)
  72455. * @param textureType Type of textures used when performing the post process. (default: 0)
  72456. */
  72457. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  72458. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72459. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72460. _this.kernel = kernel;
  72461. _this.onApply = function (effect) {
  72462. effect.setFloat2("screenSize", _this.width, _this.height);
  72463. effect.setArray("kernel", _this.kernel);
  72464. };
  72465. return _this;
  72466. }
  72467. // Statics
  72468. /**
  72469. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72470. */
  72471. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  72472. /**
  72473. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72474. */
  72475. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  72476. /**
  72477. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72478. */
  72479. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  72480. /**
  72481. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72482. */
  72483. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  72484. /**
  72485. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72486. */
  72487. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  72488. /**
  72489. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  72490. */
  72491. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  72492. return ConvolutionPostProcess;
  72493. }(BABYLON.PostProcess));
  72494. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  72495. })(BABYLON || (BABYLON = {}));
  72496. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  72497. "use strict";
  72498. var BABYLON;
  72499. (function (BABYLON) {
  72500. var FilterPostProcess = /** @class */ (function (_super) {
  72501. __extends(FilterPostProcess, _super);
  72502. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  72503. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  72504. _this.kernelMatrix = kernelMatrix;
  72505. _this.onApply = function (effect) {
  72506. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  72507. };
  72508. return _this;
  72509. }
  72510. return FilterPostProcess;
  72511. }(BABYLON.PostProcess));
  72512. BABYLON.FilterPostProcess = FilterPostProcess;
  72513. })(BABYLON || (BABYLON = {}));
  72514. //# sourceMappingURL=babylon.filterPostProcess.js.map
  72515. "use strict";
  72516. var BABYLON;
  72517. (function (BABYLON) {
  72518. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  72519. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  72520. __extends(VolumetricLightScatteringPostProcess, _super);
  72521. /**
  72522. * @constructor
  72523. * @param {string} name - The post-process name
  72524. * @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)
  72525. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  72526. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  72527. * @param {number} samples - The post-process quality, default 100
  72528. * @param {number} samplingMode - The post-process filtering mode
  72529. * @param {BABYLON.Engine} engine - The babylon engine
  72530. * @param {boolean} reusable - If the post-process is reusable
  72531. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  72532. */
  72533. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  72534. if (samples === void 0) { samples = 100; }
  72535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72536. 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;
  72537. _this._screenCoordinates = BABYLON.Vector2.Zero();
  72538. /**
  72539. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  72540. */
  72541. _this.customMeshPosition = BABYLON.Vector3.Zero();
  72542. /**
  72543. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  72544. */
  72545. _this.useCustomMeshPosition = false;
  72546. /**
  72547. * If the post-process should inverse the light scattering direction
  72548. */
  72549. _this.invert = true;
  72550. /**
  72551. * Array containing the excluded meshes not rendered in the internal pass
  72552. */
  72553. _this.excludedMeshes = new Array();
  72554. /**
  72555. * Controls the overall intensity of the post-process
  72556. */
  72557. _this.exposure = 0.3;
  72558. /**
  72559. * Dissipates each sample's contribution in range [0, 1]
  72560. */
  72561. _this.decay = 0.96815;
  72562. /**
  72563. * Controls the overall intensity of each sample
  72564. */
  72565. _this.weight = 0.58767;
  72566. /**
  72567. * Controls the density of each sample
  72568. */
  72569. _this.density = 0.926;
  72570. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  72571. engine = scene.getEngine();
  72572. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  72573. // Configure mesh
  72574. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  72575. // Configure
  72576. _this._createPass(scene, ratio.passRatio || ratio);
  72577. _this.onActivate = function (camera) {
  72578. if (!_this.isSupported) {
  72579. _this.dispose(camera);
  72580. }
  72581. _this.onActivate = null;
  72582. };
  72583. _this.onApplyObservable.add(function (effect) {
  72584. _this._updateMeshScreenCoordinates(scene);
  72585. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  72586. effect.setFloat("exposure", _this.exposure);
  72587. effect.setFloat("decay", _this.decay);
  72588. effect.setFloat("weight", _this.weight);
  72589. effect.setFloat("density", _this.density);
  72590. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  72591. });
  72592. return _this;
  72593. }
  72594. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  72595. get: function () {
  72596. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  72597. return false;
  72598. },
  72599. set: function (useDiffuseColor) {
  72600. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  72601. },
  72602. enumerable: true,
  72603. configurable: true
  72604. });
  72605. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  72606. return "VolumetricLightScatteringPostProcess";
  72607. };
  72608. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  72609. var mesh = subMesh.getMesh();
  72610. // Render this.mesh as default
  72611. if (mesh === this.mesh && mesh.material) {
  72612. return mesh.material.isReady(mesh);
  72613. }
  72614. var defines = [];
  72615. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72616. var material = subMesh.getMaterial();
  72617. // Alpha test
  72618. if (material) {
  72619. if (material.needAlphaTesting()) {
  72620. defines.push("#define ALPHATEST");
  72621. }
  72622. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72623. attribs.push(BABYLON.VertexBuffer.UVKind);
  72624. defines.push("#define UV1");
  72625. }
  72626. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72627. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72628. defines.push("#define UV2");
  72629. }
  72630. }
  72631. // Bones
  72632. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72633. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72634. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72635. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72636. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72637. }
  72638. else {
  72639. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72640. }
  72641. // Instances
  72642. if (useInstances) {
  72643. defines.push("#define INSTANCES");
  72644. attribs.push("world0");
  72645. attribs.push("world1");
  72646. attribs.push("world2");
  72647. attribs.push("world3");
  72648. }
  72649. // Get correct effect
  72650. var join = defines.join("\n");
  72651. if (this._cachedDefines !== join) {
  72652. this._cachedDefines = join;
  72653. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  72654. }
  72655. return this._volumetricLightScatteringPass.isReady();
  72656. };
  72657. /**
  72658. * Sets the new light position for light scattering effect
  72659. * @param {BABYLON.Vector3} The new custom light position
  72660. */
  72661. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  72662. this.customMeshPosition = position;
  72663. };
  72664. /**
  72665. * Returns the light position for light scattering effect
  72666. * @return {BABYLON.Vector3} The custom light position
  72667. */
  72668. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  72669. return this.customMeshPosition;
  72670. };
  72671. /**
  72672. * Disposes the internal assets and detaches the post-process from the camera
  72673. */
  72674. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  72675. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  72676. if (rttIndex !== -1) {
  72677. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  72678. }
  72679. this._volumetricLightScatteringRTT.dispose();
  72680. _super.prototype.dispose.call(this, camera);
  72681. };
  72682. /**
  72683. * Returns the render target texture used by the post-process
  72684. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  72685. */
  72686. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  72687. return this._volumetricLightScatteringRTT;
  72688. };
  72689. // Private methods
  72690. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  72691. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  72692. return true;
  72693. }
  72694. return false;
  72695. };
  72696. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  72697. var _this = this;
  72698. var engine = scene.getEngine();
  72699. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72700. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72701. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72702. this._volumetricLightScatteringRTT.renderList = null;
  72703. this._volumetricLightScatteringRTT.renderParticles = false;
  72704. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  72705. var camera = this.getCamera();
  72706. if (camera) {
  72707. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72708. }
  72709. else {
  72710. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  72711. }
  72712. // Custom render function for submeshes
  72713. var renderSubMesh = function (subMesh) {
  72714. var mesh = subMesh.getRenderingMesh();
  72715. if (_this._meshExcluded(mesh)) {
  72716. return;
  72717. }
  72718. var material = subMesh.getMaterial();
  72719. if (!material) {
  72720. return;
  72721. }
  72722. var scene = mesh.getScene();
  72723. var engine = scene.getEngine();
  72724. // Culling
  72725. engine.setState(material.backFaceCulling);
  72726. // Managing instances
  72727. var batch = mesh._getInstancesRenderList(subMesh._id);
  72728. if (batch.mustReturn) {
  72729. return;
  72730. }
  72731. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72732. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  72733. var effect = _this._volumetricLightScatteringPass;
  72734. if (mesh === _this.mesh) {
  72735. if (subMesh.effect) {
  72736. effect = subMesh.effect;
  72737. }
  72738. else {
  72739. effect = material.getEffect();
  72740. }
  72741. }
  72742. engine.enableEffect(effect);
  72743. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  72744. if (mesh === _this.mesh) {
  72745. material.bind(mesh.getWorldMatrix(), mesh);
  72746. }
  72747. else {
  72748. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  72749. // Alpha test
  72750. if (material && material.needAlphaTesting()) {
  72751. var alphaTexture = material.getAlphaTestTexture();
  72752. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  72753. if (alphaTexture) {
  72754. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72755. }
  72756. }
  72757. // Bones
  72758. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72759. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72760. }
  72761. }
  72762. // Draw
  72763. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  72764. }
  72765. };
  72766. // Render target texture callbacks
  72767. var savedSceneClearColor;
  72768. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  72769. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  72770. savedSceneClearColor = scene.clearColor;
  72771. scene.clearColor = sceneClearColor;
  72772. });
  72773. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  72774. scene.clearColor = savedSceneClearColor;
  72775. });
  72776. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72777. var engine = scene.getEngine();
  72778. var index;
  72779. if (depthOnlySubMeshes.length) {
  72780. engine.setColorWrite(false);
  72781. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72782. renderSubMesh(depthOnlySubMeshes.data[index]);
  72783. }
  72784. engine.setColorWrite(true);
  72785. }
  72786. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72787. renderSubMesh(opaqueSubMeshes.data[index]);
  72788. }
  72789. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72790. renderSubMesh(alphaTestSubMeshes.data[index]);
  72791. }
  72792. if (transparentSubMeshes.length) {
  72793. // Sort sub meshes
  72794. for (index = 0; index < transparentSubMeshes.length; index++) {
  72795. var submesh = transparentSubMeshes.data[index];
  72796. var boundingInfo = submesh.getBoundingInfo();
  72797. if (boundingInfo && scene.activeCamera) {
  72798. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  72799. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  72800. }
  72801. }
  72802. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  72803. sortedArray.sort(function (a, b) {
  72804. // Alpha index first
  72805. if (a._alphaIndex > b._alphaIndex) {
  72806. return 1;
  72807. }
  72808. if (a._alphaIndex < b._alphaIndex) {
  72809. return -1;
  72810. }
  72811. // Then distance to camera
  72812. if (a._distanceToCamera < b._distanceToCamera) {
  72813. return 1;
  72814. }
  72815. if (a._distanceToCamera > b._distanceToCamera) {
  72816. return -1;
  72817. }
  72818. return 0;
  72819. });
  72820. // Render sub meshes
  72821. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  72822. for (index = 0; index < sortedArray.length; index++) {
  72823. renderSubMesh(sortedArray[index]);
  72824. }
  72825. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72826. }
  72827. };
  72828. };
  72829. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  72830. var transform = scene.getTransformMatrix();
  72831. var meshPosition;
  72832. if (this.useCustomMeshPosition) {
  72833. meshPosition = this.customMeshPosition;
  72834. }
  72835. else if (this.attachedNode) {
  72836. meshPosition = this.attachedNode.position;
  72837. }
  72838. else {
  72839. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  72840. }
  72841. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  72842. this._screenCoordinates.x = pos.x / this._viewPort.width;
  72843. this._screenCoordinates.y = pos.y / this._viewPort.height;
  72844. if (this.invert)
  72845. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  72846. };
  72847. // Static methods
  72848. /**
  72849. * Creates a default mesh for the Volumeric Light Scattering post-process
  72850. * @param {string} The mesh name
  72851. * @param {BABYLON.Scene} The scene where to create the mesh
  72852. * @return {BABYLON.Mesh} the default mesh
  72853. */
  72854. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  72855. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  72856. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  72857. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  72858. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  72859. mesh.material = material;
  72860. return mesh;
  72861. };
  72862. __decorate([
  72863. BABYLON.serializeAsVector3()
  72864. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  72865. __decorate([
  72866. BABYLON.serialize()
  72867. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  72868. __decorate([
  72869. BABYLON.serialize()
  72870. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  72871. __decorate([
  72872. BABYLON.serializeAsMeshReference()
  72873. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  72874. __decorate([
  72875. BABYLON.serialize()
  72876. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  72877. __decorate([
  72878. BABYLON.serialize()
  72879. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  72880. __decorate([
  72881. BABYLON.serialize()
  72882. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  72883. __decorate([
  72884. BABYLON.serialize()
  72885. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  72886. __decorate([
  72887. BABYLON.serialize()
  72888. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  72889. return VolumetricLightScatteringPostProcess;
  72890. }(BABYLON.PostProcess));
  72891. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  72892. })(BABYLON || (BABYLON = {}));
  72893. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  72894. "use strict";
  72895. //
  72896. // This post-process allows the modification of rendered colors by using
  72897. // a 'look-up table' (LUT). This effect is also called Color Grading.
  72898. //
  72899. // The object needs to be provided an url to a texture containing the color
  72900. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  72901. // Use an image editing software to tweak the LUT to match your needs.
  72902. //
  72903. // For an example of a color LUT, see here:
  72904. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  72905. // For explanations on color grading, see here:
  72906. // http://udn.epicgames.com/Three/ColorGrading.html
  72907. //
  72908. var BABYLON;
  72909. (function (BABYLON) {
  72910. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  72911. __extends(ColorCorrectionPostProcess, _super);
  72912. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  72913. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  72914. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72915. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  72916. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72917. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72918. _this.onApply = function (effect) {
  72919. effect.setTexture("colorTable", _this._colorTableTexture);
  72920. };
  72921. return _this;
  72922. }
  72923. return ColorCorrectionPostProcess;
  72924. }(BABYLON.PostProcess));
  72925. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  72926. })(BABYLON || (BABYLON = {}));
  72927. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  72928. "use strict";
  72929. var BABYLON;
  72930. (function (BABYLON) {
  72931. var TonemappingOperator;
  72932. (function (TonemappingOperator) {
  72933. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72934. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72935. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72936. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72937. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72938. ;
  72939. var TonemapPostProcess = /** @class */ (function (_super) {
  72940. __extends(TonemapPostProcess, _super);
  72941. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72943. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72944. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72945. _this._operator = _operator;
  72946. _this.exposureAdjustment = exposureAdjustment;
  72947. var defines = "#define ";
  72948. if (_this._operator === TonemappingOperator.Hable)
  72949. defines += "HABLE_TONEMAPPING";
  72950. else if (_this._operator === TonemappingOperator.Reinhard)
  72951. defines += "REINHARD_TONEMAPPING";
  72952. else if (_this._operator === TonemappingOperator.HejiDawson)
  72953. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72954. else if (_this._operator === TonemappingOperator.Photographic)
  72955. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72956. //sadly a second call to create the effect.
  72957. _this.updateEffect(defines);
  72958. _this.onApply = function (effect) {
  72959. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72960. };
  72961. return _this;
  72962. }
  72963. return TonemapPostProcess;
  72964. }(BABYLON.PostProcess));
  72965. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72966. })(BABYLON || (BABYLON = {}));
  72967. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72968. "use strict";
  72969. var BABYLON;
  72970. (function (BABYLON) {
  72971. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72972. __extends(DisplayPassPostProcess, _super);
  72973. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72974. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72975. }
  72976. return DisplayPassPostProcess;
  72977. }(BABYLON.PostProcess));
  72978. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72979. })(BABYLON || (BABYLON = {}));
  72980. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72981. "use strict";
  72982. var BABYLON;
  72983. (function (BABYLON) {
  72984. var HighlightsPostProcess = /** @class */ (function (_super) {
  72985. __extends(HighlightsPostProcess, _super);
  72986. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72987. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72988. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72989. }
  72990. return HighlightsPostProcess;
  72991. }(BABYLON.PostProcess));
  72992. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72993. })(BABYLON || (BABYLON = {}));
  72994. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72995. "use strict";
  72996. var BABYLON;
  72997. (function (BABYLON) {
  72998. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72999. __extends(ImageProcessingPostProcess, _super);
  73000. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  73001. if (camera === void 0) { camera = null; }
  73002. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73003. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  73004. _this._fromLinearSpace = true;
  73005. /**
  73006. * Defines cache preventing GC.
  73007. */
  73008. _this._defines = {
  73009. IMAGEPROCESSING: false,
  73010. VIGNETTE: false,
  73011. VIGNETTEBLENDMODEMULTIPLY: false,
  73012. VIGNETTEBLENDMODEOPAQUE: false,
  73013. TONEMAPPING: false,
  73014. CONTRAST: false,
  73015. COLORCURVES: false,
  73016. COLORGRADING: false,
  73017. COLORGRADING3D: false,
  73018. FROMLINEARSPACE: false,
  73019. SAMPLER3DGREENDEPTH: false,
  73020. SAMPLER3DBGRMAP: false,
  73021. IMAGEPROCESSINGPOSTPROCESS: false,
  73022. EXPOSURE: false,
  73023. };
  73024. // Setup the configuration as forced by the constructor. This would then not force the
  73025. // scene materials output in linear space and let untouched the default forward pass.
  73026. if (imageProcessingConfiguration) {
  73027. imageProcessingConfiguration.applyByPostProcess = true;
  73028. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  73029. // This will cause the shader to be compiled
  73030. _this.fromLinearSpace = false;
  73031. }
  73032. else {
  73033. _this._attachImageProcessingConfiguration(null, true);
  73034. _this.imageProcessingConfiguration.applyByPostProcess = true;
  73035. }
  73036. _this.onApply = function (effect) {
  73037. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  73038. };
  73039. return _this;
  73040. }
  73041. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  73042. /**
  73043. * Gets the image processing configuration used either in this material.
  73044. */
  73045. get: function () {
  73046. return this._imageProcessingConfiguration;
  73047. },
  73048. /**
  73049. * Sets the Default image processing configuration used either in the this material.
  73050. *
  73051. * If sets to null, the scene one is in use.
  73052. */
  73053. set: function (value) {
  73054. this._attachImageProcessingConfiguration(value);
  73055. },
  73056. enumerable: true,
  73057. configurable: true
  73058. });
  73059. /**
  73060. * Attaches a new image processing configuration to the PBR Material.
  73061. * @param configuration
  73062. */
  73063. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  73064. var _this = this;
  73065. if (doNotBuild === void 0) { doNotBuild = false; }
  73066. if (configuration === this._imageProcessingConfiguration) {
  73067. return;
  73068. }
  73069. // Detaches observer.
  73070. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  73071. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  73072. }
  73073. // Pick the scene configuration if needed.
  73074. if (!configuration) {
  73075. var scene = null;
  73076. var engine = this.getEngine();
  73077. var camera = this.getCamera();
  73078. if (camera) {
  73079. scene = camera.getScene();
  73080. }
  73081. else if (engine && engine.scenes) {
  73082. var scenes = engine.scenes;
  73083. scene = scenes[scenes.length - 1];
  73084. }
  73085. else {
  73086. scene = BABYLON.Engine.LastCreatedScene;
  73087. }
  73088. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  73089. }
  73090. else {
  73091. this._imageProcessingConfiguration = configuration;
  73092. }
  73093. // Attaches observer.
  73094. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  73095. _this._updateParameters();
  73096. });
  73097. // Ensure the effect will be rebuilt.
  73098. if (!doNotBuild) {
  73099. this._updateParameters();
  73100. }
  73101. };
  73102. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  73103. /**
  73104. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  73105. */
  73106. get: function () {
  73107. return this.imageProcessingConfiguration.colorCurves;
  73108. },
  73109. /**
  73110. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  73111. */
  73112. set: function (value) {
  73113. this.imageProcessingConfiguration.colorCurves = value;
  73114. },
  73115. enumerable: true,
  73116. configurable: true
  73117. });
  73118. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  73119. /**
  73120. * Gets wether the color curves effect is enabled.
  73121. */
  73122. get: function () {
  73123. return this.imageProcessingConfiguration.colorCurvesEnabled;
  73124. },
  73125. /**
  73126. * Sets wether the color curves effect is enabled.
  73127. */
  73128. set: function (value) {
  73129. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  73130. },
  73131. enumerable: true,
  73132. configurable: true
  73133. });
  73134. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  73135. /**
  73136. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  73137. */
  73138. get: function () {
  73139. return this.imageProcessingConfiguration.colorGradingTexture;
  73140. },
  73141. /**
  73142. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  73143. */
  73144. set: function (value) {
  73145. this.imageProcessingConfiguration.colorGradingTexture = value;
  73146. },
  73147. enumerable: true,
  73148. configurable: true
  73149. });
  73150. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  73151. /**
  73152. * Gets wether the color grading effect is enabled.
  73153. */
  73154. get: function () {
  73155. return this.imageProcessingConfiguration.colorGradingEnabled;
  73156. },
  73157. /**
  73158. * Gets wether the color grading effect is enabled.
  73159. */
  73160. set: function (value) {
  73161. this.imageProcessingConfiguration.colorGradingEnabled = value;
  73162. },
  73163. enumerable: true,
  73164. configurable: true
  73165. });
  73166. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  73167. /**
  73168. * Gets exposure used in the effect.
  73169. */
  73170. get: function () {
  73171. return this.imageProcessingConfiguration.exposure;
  73172. },
  73173. /**
  73174. * Sets exposure used in the effect.
  73175. */
  73176. set: function (value) {
  73177. this.imageProcessingConfiguration.exposure = value;
  73178. },
  73179. enumerable: true,
  73180. configurable: true
  73181. });
  73182. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  73183. /**
  73184. * Gets wether tonemapping is enabled or not.
  73185. */
  73186. get: function () {
  73187. return this._imageProcessingConfiguration.toneMappingEnabled;
  73188. },
  73189. /**
  73190. * Sets wether tonemapping is enabled or not
  73191. */
  73192. set: function (value) {
  73193. this._imageProcessingConfiguration.toneMappingEnabled = value;
  73194. },
  73195. enumerable: true,
  73196. configurable: true
  73197. });
  73198. ;
  73199. ;
  73200. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  73201. /**
  73202. * Gets contrast used in the effect.
  73203. */
  73204. get: function () {
  73205. return this.imageProcessingConfiguration.contrast;
  73206. },
  73207. /**
  73208. * Sets contrast used in the effect.
  73209. */
  73210. set: function (value) {
  73211. this.imageProcessingConfiguration.contrast = value;
  73212. },
  73213. enumerable: true,
  73214. configurable: true
  73215. });
  73216. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  73217. /**
  73218. * Gets Vignette stretch size.
  73219. */
  73220. get: function () {
  73221. return this.imageProcessingConfiguration.vignetteStretch;
  73222. },
  73223. /**
  73224. * Sets Vignette stretch size.
  73225. */
  73226. set: function (value) {
  73227. this.imageProcessingConfiguration.vignetteStretch = value;
  73228. },
  73229. enumerable: true,
  73230. configurable: true
  73231. });
  73232. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  73233. /**
  73234. * Gets Vignette centre X Offset.
  73235. */
  73236. get: function () {
  73237. return this.imageProcessingConfiguration.vignetteCentreX;
  73238. },
  73239. /**
  73240. * Sets Vignette centre X Offset.
  73241. */
  73242. set: function (value) {
  73243. this.imageProcessingConfiguration.vignetteCentreX = value;
  73244. },
  73245. enumerable: true,
  73246. configurable: true
  73247. });
  73248. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  73249. /**
  73250. * Gets Vignette centre Y Offset.
  73251. */
  73252. get: function () {
  73253. return this.imageProcessingConfiguration.vignetteCentreY;
  73254. },
  73255. /**
  73256. * Sets Vignette centre Y Offset.
  73257. */
  73258. set: function (value) {
  73259. this.imageProcessingConfiguration.vignetteCentreY = value;
  73260. },
  73261. enumerable: true,
  73262. configurable: true
  73263. });
  73264. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  73265. /**
  73266. * Gets Vignette weight or intensity of the vignette effect.
  73267. */
  73268. get: function () {
  73269. return this.imageProcessingConfiguration.vignetteWeight;
  73270. },
  73271. /**
  73272. * Sets Vignette weight or intensity of the vignette effect.
  73273. */
  73274. set: function (value) {
  73275. this.imageProcessingConfiguration.vignetteWeight = value;
  73276. },
  73277. enumerable: true,
  73278. configurable: true
  73279. });
  73280. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  73281. /**
  73282. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  73283. * if vignetteEnabled is set to true.
  73284. */
  73285. get: function () {
  73286. return this.imageProcessingConfiguration.vignetteColor;
  73287. },
  73288. /**
  73289. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  73290. * if vignetteEnabled is set to true.
  73291. */
  73292. set: function (value) {
  73293. this.imageProcessingConfiguration.vignetteColor = value;
  73294. },
  73295. enumerable: true,
  73296. configurable: true
  73297. });
  73298. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  73299. /**
  73300. * Gets Camera field of view used by the Vignette effect.
  73301. */
  73302. get: function () {
  73303. return this.imageProcessingConfiguration.vignetteCameraFov;
  73304. },
  73305. /**
  73306. * Sets Camera field of view used by the Vignette effect.
  73307. */
  73308. set: function (value) {
  73309. this.imageProcessingConfiguration.vignetteCameraFov = value;
  73310. },
  73311. enumerable: true,
  73312. configurable: true
  73313. });
  73314. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  73315. /**
  73316. * Gets the vignette blend mode allowing different kind of effect.
  73317. */
  73318. get: function () {
  73319. return this.imageProcessingConfiguration.vignetteBlendMode;
  73320. },
  73321. /**
  73322. * Sets the vignette blend mode allowing different kind of effect.
  73323. */
  73324. set: function (value) {
  73325. this.imageProcessingConfiguration.vignetteBlendMode = value;
  73326. },
  73327. enumerable: true,
  73328. configurable: true
  73329. });
  73330. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  73331. /**
  73332. * Gets wether the vignette effect is enabled.
  73333. */
  73334. get: function () {
  73335. return this.imageProcessingConfiguration.vignetteEnabled;
  73336. },
  73337. /**
  73338. * Sets wether the vignette effect is enabled.
  73339. */
  73340. set: function (value) {
  73341. this.imageProcessingConfiguration.vignetteEnabled = value;
  73342. },
  73343. enumerable: true,
  73344. configurable: true
  73345. });
  73346. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  73347. /**
  73348. * Gets wether the input of the processing is in Gamma or Linear Space.
  73349. */
  73350. get: function () {
  73351. return this._fromLinearSpace;
  73352. },
  73353. /**
  73354. * Sets wether the input of the processing is in Gamma or Linear Space.
  73355. */
  73356. set: function (value) {
  73357. if (this._fromLinearSpace === value) {
  73358. return;
  73359. }
  73360. this._fromLinearSpace = value;
  73361. this._updateParameters();
  73362. },
  73363. enumerable: true,
  73364. configurable: true
  73365. });
  73366. ImageProcessingPostProcess.prototype.getClassName = function () {
  73367. return "ImageProcessingPostProcess";
  73368. };
  73369. ImageProcessingPostProcess.prototype._updateParameters = function () {
  73370. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  73371. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  73372. var defines = "";
  73373. for (var define in this._defines) {
  73374. if (this._defines[define]) {
  73375. defines += "#define " + define + ";\r\n";
  73376. }
  73377. }
  73378. var samplers = ["textureSampler"];
  73379. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  73380. var uniforms = ["scale"];
  73381. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  73382. this.updateEffect(defines, uniforms, samplers);
  73383. };
  73384. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  73385. _super.prototype.dispose.call(this, camera);
  73386. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  73387. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  73388. }
  73389. this.imageProcessingConfiguration.applyByPostProcess = false;
  73390. };
  73391. __decorate([
  73392. BABYLON.serialize()
  73393. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  73394. return ImageProcessingPostProcess;
  73395. }(BABYLON.PostProcess));
  73396. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  73397. })(BABYLON || (BABYLON = {}));
  73398. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  73399. "use strict";
  73400. var BABYLON;
  73401. (function (BABYLON) {
  73402. var Bone = /** @class */ (function (_super) {
  73403. __extends(Bone, _super);
  73404. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  73405. if (parentBone === void 0) { parentBone = null; }
  73406. if (localMatrix === void 0) { localMatrix = null; }
  73407. if (restPose === void 0) { restPose = null; }
  73408. if (baseMatrix === void 0) { baseMatrix = null; }
  73409. if (index === void 0) { index = null; }
  73410. var _this = _super.call(this, name, skeleton.getScene()) || this;
  73411. _this.name = name;
  73412. _this.children = new Array();
  73413. _this.animations = new Array();
  73414. // Set this value to map this bone to a different index in the transform matrices.
  73415. // Set this value to -1 to exclude the bone from the transform matrices.
  73416. _this._index = null;
  73417. _this._worldTransform = new BABYLON.Matrix();
  73418. _this._absoluteTransform = new BABYLON.Matrix();
  73419. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  73420. _this._scaleMatrix = BABYLON.Matrix.Identity();
  73421. _this._scaleVector = BABYLON.Vector3.One();
  73422. _this._negateScaleChildren = BABYLON.Vector3.One();
  73423. _this._scalingDeterminant = 1;
  73424. _this._skeleton = skeleton;
  73425. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  73426. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  73427. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  73428. _this._index = index;
  73429. skeleton.bones.push(_this);
  73430. _this.setParent(parentBone, false);
  73431. _this._updateDifferenceMatrix();
  73432. return _this;
  73433. }
  73434. Object.defineProperty(Bone.prototype, "_matrix", {
  73435. get: function () {
  73436. return this._localMatrix;
  73437. },
  73438. set: function (val) {
  73439. if (this._localMatrix) {
  73440. this._localMatrix.copyFrom(val);
  73441. }
  73442. else {
  73443. this._localMatrix = val;
  73444. }
  73445. },
  73446. enumerable: true,
  73447. configurable: true
  73448. });
  73449. // Members
  73450. Bone.prototype.getSkeleton = function () {
  73451. return this._skeleton;
  73452. };
  73453. Bone.prototype.getParent = function () {
  73454. return this._parent;
  73455. };
  73456. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  73457. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  73458. if (this._parent === parent) {
  73459. return;
  73460. }
  73461. if (this._parent) {
  73462. var index = this._parent.children.indexOf(this);
  73463. if (index !== -1) {
  73464. this._parent.children.splice(index, 1);
  73465. }
  73466. }
  73467. this._parent = parent;
  73468. if (this._parent) {
  73469. this._parent.children.push(this);
  73470. }
  73471. if (updateDifferenceMatrix) {
  73472. this._updateDifferenceMatrix();
  73473. }
  73474. };
  73475. Bone.prototype.getLocalMatrix = function () {
  73476. return this._localMatrix;
  73477. };
  73478. Bone.prototype.getBaseMatrix = function () {
  73479. return this._baseMatrix;
  73480. };
  73481. Bone.prototype.getRestPose = function () {
  73482. return this._restPose;
  73483. };
  73484. Bone.prototype.returnToRest = function () {
  73485. this.updateMatrix(this._restPose.clone());
  73486. };
  73487. Bone.prototype.getWorldMatrix = function () {
  73488. return this._worldTransform;
  73489. };
  73490. Bone.prototype.getInvertedAbsoluteTransform = function () {
  73491. return this._invertedAbsoluteTransform;
  73492. };
  73493. Bone.prototype.getAbsoluteTransform = function () {
  73494. return this._absoluteTransform;
  73495. };
  73496. Object.defineProperty(Bone.prototype, "position", {
  73497. // Properties (matches AbstractMesh properties)
  73498. get: function () {
  73499. return this.getPosition();
  73500. },
  73501. set: function (newPosition) {
  73502. this.setPosition(newPosition);
  73503. },
  73504. enumerable: true,
  73505. configurable: true
  73506. });
  73507. Object.defineProperty(Bone.prototype, "rotation", {
  73508. get: function () {
  73509. return this.getRotation();
  73510. },
  73511. set: function (newRotation) {
  73512. this.setRotation(newRotation);
  73513. },
  73514. enumerable: true,
  73515. configurable: true
  73516. });
  73517. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  73518. get: function () {
  73519. return this.getRotationQuaternion();
  73520. },
  73521. set: function (newRotation) {
  73522. this.setRotationQuaternion(newRotation);
  73523. },
  73524. enumerable: true,
  73525. configurable: true
  73526. });
  73527. Object.defineProperty(Bone.prototype, "scaling", {
  73528. get: function () {
  73529. return this.getScale();
  73530. },
  73531. set: function (newScaling) {
  73532. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  73533. },
  73534. enumerable: true,
  73535. configurable: true
  73536. });
  73537. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  73538. /**
  73539. * Gets the animation properties override
  73540. */
  73541. get: function () {
  73542. return this._skeleton.animationPropertiesOverride;
  73543. },
  73544. enumerable: true,
  73545. configurable: true
  73546. });
  73547. // Methods
  73548. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  73549. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  73550. this._baseMatrix = matrix.clone();
  73551. this._localMatrix = matrix.clone();
  73552. this._skeleton._markAsDirty();
  73553. if (updateDifferenceMatrix) {
  73554. this._updateDifferenceMatrix();
  73555. }
  73556. };
  73557. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  73558. if (!rootMatrix) {
  73559. rootMatrix = this._baseMatrix;
  73560. }
  73561. if (this._parent) {
  73562. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73563. }
  73564. else {
  73565. this._absoluteTransform.copyFrom(rootMatrix);
  73566. }
  73567. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  73568. for (var index = 0; index < this.children.length; index++) {
  73569. this.children[index]._updateDifferenceMatrix();
  73570. }
  73571. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  73572. };
  73573. Bone.prototype.markAsDirty = function () {
  73574. this._currentRenderId++;
  73575. this._childRenderId++;
  73576. this._skeleton._markAsDirty();
  73577. };
  73578. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  73579. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73580. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  73581. // all animation may be coming from a library skeleton, so may need to create animation
  73582. if (this.animations.length === 0) {
  73583. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  73584. this.animations[0].setKeys([]);
  73585. }
  73586. // get animation info / verify there is such a range from the source bone
  73587. var sourceRange = source.animations[0].getRange(rangeName);
  73588. if (!sourceRange) {
  73589. return false;
  73590. }
  73591. var from = sourceRange.from;
  73592. var to = sourceRange.to;
  73593. var sourceKeys = source.animations[0].getKeys();
  73594. // rescaling prep
  73595. var sourceBoneLength = source.length;
  73596. var sourceParent = source.getParent();
  73597. var parent = this.getParent();
  73598. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  73599. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  73600. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  73601. var destKeys = this.animations[0].getKeys();
  73602. // loop vars declaration
  73603. var orig;
  73604. var origTranslation;
  73605. var mat;
  73606. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  73607. orig = sourceKeys[key];
  73608. if (orig.frame >= from && orig.frame <= to) {
  73609. if (rescaleAsRequired) {
  73610. mat = orig.value.clone();
  73611. // scale based on parent ratio, when bone has parent
  73612. if (parentScalingReqd) {
  73613. origTranslation = mat.getTranslation();
  73614. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  73615. // scale based on skeleton dimension ratio when root bone, and value is passed
  73616. }
  73617. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  73618. origTranslation = mat.getTranslation();
  73619. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  73620. // use original when root bone, and no data for skelDimensionsRatio
  73621. }
  73622. else {
  73623. mat = orig.value;
  73624. }
  73625. }
  73626. else {
  73627. mat = orig.value;
  73628. }
  73629. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  73630. }
  73631. }
  73632. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  73633. return true;
  73634. };
  73635. /**
  73636. * Translate the bone in local or world space.
  73637. * @param vec The amount to translate the bone.
  73638. * @param space The space that the translation is in.
  73639. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73640. */
  73641. Bone.prototype.translate = function (vec, space, mesh) {
  73642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73643. var lm = this.getLocalMatrix();
  73644. if (space == BABYLON.Space.LOCAL) {
  73645. lm.m[12] += vec.x;
  73646. lm.m[13] += vec.y;
  73647. lm.m[14] += vec.z;
  73648. }
  73649. else {
  73650. var wm = null;
  73651. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73652. if (mesh) {
  73653. wm = mesh.getWorldMatrix();
  73654. }
  73655. this._skeleton.computeAbsoluteTransforms();
  73656. var tmat = Bone._tmpMats[0];
  73657. var tvec = Bone._tmpVecs[0];
  73658. if (this._parent) {
  73659. if (mesh && wm) {
  73660. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73661. tmat.multiplyToRef(wm, tmat);
  73662. }
  73663. else {
  73664. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73665. }
  73666. }
  73667. tmat.m[12] = 0;
  73668. tmat.m[13] = 0;
  73669. tmat.m[14] = 0;
  73670. tmat.invert();
  73671. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  73672. lm.m[12] += tvec.x;
  73673. lm.m[13] += tvec.y;
  73674. lm.m[14] += tvec.z;
  73675. }
  73676. this.markAsDirty();
  73677. };
  73678. /**
  73679. * Set the postion of the bone in local or world space.
  73680. * @param position The position to set the bone.
  73681. * @param space The space that the position is in.
  73682. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73683. */
  73684. Bone.prototype.setPosition = function (position, space, mesh) {
  73685. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73686. var lm = this.getLocalMatrix();
  73687. if (space == BABYLON.Space.LOCAL) {
  73688. lm.m[12] = position.x;
  73689. lm.m[13] = position.y;
  73690. lm.m[14] = position.z;
  73691. }
  73692. else {
  73693. var wm = null;
  73694. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73695. if (mesh) {
  73696. wm = mesh.getWorldMatrix();
  73697. }
  73698. this._skeleton.computeAbsoluteTransforms();
  73699. var tmat = Bone._tmpMats[0];
  73700. var vec = Bone._tmpVecs[0];
  73701. if (this._parent) {
  73702. if (mesh && wm) {
  73703. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73704. tmat.multiplyToRef(wm, tmat);
  73705. }
  73706. else {
  73707. tmat.copyFrom(this._parent.getAbsoluteTransform());
  73708. }
  73709. }
  73710. tmat.invert();
  73711. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  73712. lm.m[12] = vec.x;
  73713. lm.m[13] = vec.y;
  73714. lm.m[14] = vec.z;
  73715. }
  73716. this.markAsDirty();
  73717. };
  73718. /**
  73719. * Set the absolute postion of the bone (world space).
  73720. * @param position The position to set the bone.
  73721. * @param mesh The mesh that this bone is attached to.
  73722. */
  73723. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  73724. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  73725. };
  73726. /**
  73727. * Set the scale of the bone on the x, y and z axes.
  73728. * @param x The scale of the bone on the x axis.
  73729. * @param x The scale of the bone on the y axis.
  73730. * @param z The scale of the bone on the z axis.
  73731. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73732. */
  73733. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  73734. if (scaleChildren === void 0) { scaleChildren = false; }
  73735. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  73736. if (!scaleChildren) {
  73737. this._negateScaleChildren.x = 1 / x;
  73738. this._negateScaleChildren.y = 1 / y;
  73739. this._negateScaleChildren.z = 1 / z;
  73740. }
  73741. this._syncScaleVector();
  73742. }
  73743. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  73744. };
  73745. /**
  73746. * Scale the bone on the x, y and z axes.
  73747. * @param x The amount to scale the bone on the x axis.
  73748. * @param x The amount to scale the bone on the y axis.
  73749. * @param z The amount to scale the bone on the z axis.
  73750. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73751. */
  73752. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  73753. if (scaleChildren === void 0) { scaleChildren = false; }
  73754. var locMat = this.getLocalMatrix();
  73755. var origLocMat = Bone._tmpMats[0];
  73756. origLocMat.copyFrom(locMat);
  73757. var origLocMatInv = Bone._tmpMats[1];
  73758. origLocMatInv.copyFrom(origLocMat);
  73759. origLocMatInv.invert();
  73760. var scaleMat = Bone._tmpMats[2];
  73761. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  73762. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  73763. this._scaleVector.x *= x;
  73764. this._scaleVector.y *= y;
  73765. this._scaleVector.z *= z;
  73766. locMat.multiplyToRef(origLocMatInv, locMat);
  73767. locMat.multiplyToRef(scaleMat, locMat);
  73768. locMat.multiplyToRef(origLocMat, locMat);
  73769. var parent = this.getParent();
  73770. if (parent) {
  73771. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  73772. }
  73773. else {
  73774. this.getAbsoluteTransform().copyFrom(locMat);
  73775. }
  73776. var len = this.children.length;
  73777. scaleMat.invert();
  73778. for (var i = 0; i < len; i++) {
  73779. var child = this.children[i];
  73780. var cm = child.getLocalMatrix();
  73781. cm.multiplyToRef(scaleMat, cm);
  73782. var lm = child.getLocalMatrix();
  73783. lm.m[12] *= x;
  73784. lm.m[13] *= y;
  73785. lm.m[14] *= z;
  73786. }
  73787. this.computeAbsoluteTransforms();
  73788. if (scaleChildren) {
  73789. for (var i = 0; i < len; i++) {
  73790. this.children[i].scale(x, y, z, scaleChildren);
  73791. }
  73792. }
  73793. this.markAsDirty();
  73794. };
  73795. /**
  73796. * Set the yaw, pitch, and roll of the bone in local or world space.
  73797. * @param yaw The rotation of the bone on the y axis.
  73798. * @param pitch The rotation of the bone on the x axis.
  73799. * @param roll The rotation of the bone on the z axis.
  73800. * @param space The space that the axes of rotation are in.
  73801. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73802. */
  73803. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  73804. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73805. var rotMat = Bone._tmpMats[0];
  73806. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  73807. var rotMatInv = Bone._tmpMats[1];
  73808. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73809. rotMatInv.multiplyToRef(rotMat, rotMat);
  73810. this._rotateWithMatrix(rotMat, space, mesh);
  73811. };
  73812. /**
  73813. * Rotate the bone on an axis in local or world space.
  73814. * @param axis The axis to rotate the bone on.
  73815. * @param amount The amount to rotate the bone.
  73816. * @param space The space that the axis is in.
  73817. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73818. */
  73819. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  73820. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73821. var rmat = Bone._tmpMats[0];
  73822. rmat.m[12] = 0;
  73823. rmat.m[13] = 0;
  73824. rmat.m[14] = 0;
  73825. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  73826. this._rotateWithMatrix(rmat, space, mesh);
  73827. };
  73828. /**
  73829. * Set the rotation of the bone to a particular axis angle in local or world space.
  73830. * @param axis The axis to rotate the bone on.
  73831. * @param angle The angle that the bone should be rotated to.
  73832. * @param space The space that the axis is in.
  73833. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73834. */
  73835. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  73836. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73837. var rotMat = Bone._tmpMats[0];
  73838. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  73839. var rotMatInv = Bone._tmpMats[1];
  73840. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73841. rotMatInv.multiplyToRef(rotMat, rotMat);
  73842. this._rotateWithMatrix(rotMat, space, mesh);
  73843. };
  73844. /**
  73845. * Set the euler rotation of the bone in local of world space.
  73846. * @param rotation The euler rotation that the bone should be set to.
  73847. * @param space The space that the rotation is in.
  73848. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73849. */
  73850. Bone.prototype.setRotation = function (rotation, space, mesh) {
  73851. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73852. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  73853. };
  73854. /**
  73855. * Set the quaternion rotation of the bone in local of world space.
  73856. * @param quat The quaternion rotation that the bone should be set to.
  73857. * @param space The space that the rotation is in.
  73858. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73859. */
  73860. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  73861. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73862. var rotMatInv = Bone._tmpMats[0];
  73863. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73864. var rotMat = Bone._tmpMats[1];
  73865. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  73866. rotMatInv.multiplyToRef(rotMat, rotMat);
  73867. this._rotateWithMatrix(rotMat, space, mesh);
  73868. };
  73869. /**
  73870. * Set the rotation matrix of the bone in local of world space.
  73871. * @param rotMat The rotation matrix that the bone should be set to.
  73872. * @param space The space that the rotation is in.
  73873. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73874. */
  73875. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  73876. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73877. var rotMatInv = Bone._tmpMats[0];
  73878. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73879. var rotMat2 = Bone._tmpMats[1];
  73880. rotMat2.copyFrom(rotMat);
  73881. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73882. this._rotateWithMatrix(rotMat2, space, mesh);
  73883. };
  73884. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73885. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73886. var lmat = this.getLocalMatrix();
  73887. var lx = lmat.m[12];
  73888. var ly = lmat.m[13];
  73889. var lz = lmat.m[14];
  73890. var parent = this.getParent();
  73891. var parentScale = Bone._tmpMats[3];
  73892. var parentScaleInv = Bone._tmpMats[4];
  73893. if (parent) {
  73894. if (space == BABYLON.Space.WORLD) {
  73895. if (mesh) {
  73896. parentScale.copyFrom(mesh.getWorldMatrix());
  73897. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73898. }
  73899. else {
  73900. parentScale.copyFrom(parent.getAbsoluteTransform());
  73901. }
  73902. }
  73903. else {
  73904. parentScale = parent._scaleMatrix;
  73905. }
  73906. parentScaleInv.copyFrom(parentScale);
  73907. parentScaleInv.invert();
  73908. lmat.multiplyToRef(parentScale, lmat);
  73909. lmat.multiplyToRef(rmat, lmat);
  73910. lmat.multiplyToRef(parentScaleInv, lmat);
  73911. }
  73912. else {
  73913. if (space == BABYLON.Space.WORLD && mesh) {
  73914. parentScale.copyFrom(mesh.getWorldMatrix());
  73915. parentScaleInv.copyFrom(parentScale);
  73916. parentScaleInv.invert();
  73917. lmat.multiplyToRef(parentScale, lmat);
  73918. lmat.multiplyToRef(rmat, lmat);
  73919. lmat.multiplyToRef(parentScaleInv, lmat);
  73920. }
  73921. else {
  73922. lmat.multiplyToRef(rmat, lmat);
  73923. }
  73924. }
  73925. lmat.m[12] = lx;
  73926. lmat.m[13] = ly;
  73927. lmat.m[14] = lz;
  73928. this.computeAbsoluteTransforms();
  73929. this.markAsDirty();
  73930. };
  73931. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73933. if (space == BABYLON.Space.WORLD) {
  73934. var scaleMatrix = Bone._tmpMats[2];
  73935. scaleMatrix.copyFrom(this._scaleMatrix);
  73936. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73937. if (mesh) {
  73938. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73939. var meshScale = Bone._tmpMats[3];
  73940. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73941. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73942. }
  73943. rotMatInv.invert();
  73944. scaleMatrix.m[0] *= this._scalingDeterminant;
  73945. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73946. }
  73947. else {
  73948. rotMatInv.copyFrom(this.getLocalMatrix());
  73949. rotMatInv.invert();
  73950. var scaleMatrix = Bone._tmpMats[2];
  73951. scaleMatrix.copyFrom(this._scaleMatrix);
  73952. if (this._parent) {
  73953. var pscaleMatrix = Bone._tmpMats[3];
  73954. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73955. pscaleMatrix.invert();
  73956. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73957. }
  73958. else {
  73959. scaleMatrix.m[0] *= this._scalingDeterminant;
  73960. }
  73961. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73962. }
  73963. };
  73964. /**
  73965. * Get the scale of the bone
  73966. * @returns the scale of the bone
  73967. */
  73968. Bone.prototype.getScale = function () {
  73969. return this._scaleVector.clone();
  73970. };
  73971. /**
  73972. * Copy the scale of the bone to a vector3.
  73973. * @param result The vector3 to copy the scale to
  73974. */
  73975. Bone.prototype.getScaleToRef = function (result) {
  73976. result.copyFrom(this._scaleVector);
  73977. };
  73978. /**
  73979. * Get the position of the bone in local or world space.
  73980. * @param space The space that the returned position is in.
  73981. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73982. * @returns The position of the bone
  73983. */
  73984. Bone.prototype.getPosition = function (space, mesh) {
  73985. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73986. if (mesh === void 0) { mesh = null; }
  73987. var pos = BABYLON.Vector3.Zero();
  73988. this.getPositionToRef(space, mesh, pos);
  73989. return pos;
  73990. };
  73991. /**
  73992. * Copy the position of the bone to a vector3 in local or world space.
  73993. * @param space The space that the returned position is in.
  73994. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73995. * @param result The vector3 to copy the position to.
  73996. */
  73997. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73998. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73999. if (space == BABYLON.Space.LOCAL) {
  74000. var lm = this.getLocalMatrix();
  74001. result.x = lm.m[12];
  74002. result.y = lm.m[13];
  74003. result.z = lm.m[14];
  74004. }
  74005. else {
  74006. var wm = null;
  74007. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  74008. if (mesh) {
  74009. wm = mesh.getWorldMatrix();
  74010. }
  74011. this._skeleton.computeAbsoluteTransforms();
  74012. var tmat = Bone._tmpMats[0];
  74013. if (mesh && wm) {
  74014. tmat.copyFrom(this.getAbsoluteTransform());
  74015. tmat.multiplyToRef(wm, tmat);
  74016. }
  74017. else {
  74018. tmat = this.getAbsoluteTransform();
  74019. }
  74020. result.x = tmat.m[12];
  74021. result.y = tmat.m[13];
  74022. result.z = tmat.m[14];
  74023. }
  74024. };
  74025. /**
  74026. * Get the absolute position of the bone (world space).
  74027. * @param mesh The mesh that this bone is attached to.
  74028. * @returns The absolute position of the bone
  74029. */
  74030. Bone.prototype.getAbsolutePosition = function (mesh) {
  74031. if (mesh === void 0) { mesh = null; }
  74032. var pos = BABYLON.Vector3.Zero();
  74033. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  74034. return pos;
  74035. };
  74036. /**
  74037. * Copy the absolute position of the bone (world space) to the result param.
  74038. * @param mesh The mesh that this bone is attached to.
  74039. * @param result The vector3 to copy the absolute position to.
  74040. */
  74041. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  74042. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  74043. };
  74044. /**
  74045. * Compute the absolute transforms of this bone and its children.
  74046. */
  74047. Bone.prototype.computeAbsoluteTransforms = function () {
  74048. if (this._parent) {
  74049. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  74050. }
  74051. else {
  74052. this._absoluteTransform.copyFrom(this._localMatrix);
  74053. var poseMatrix = this._skeleton.getPoseMatrix();
  74054. if (poseMatrix) {
  74055. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  74056. }
  74057. }
  74058. var children = this.children;
  74059. var len = children.length;
  74060. for (var i = 0; i < len; i++) {
  74061. children[i].computeAbsoluteTransforms();
  74062. }
  74063. };
  74064. Bone.prototype._syncScaleVector = function () {
  74065. var lm = this.getLocalMatrix();
  74066. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  74067. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  74068. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  74069. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  74070. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  74071. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  74072. this._scaleVector.x = xs * Math.sqrt(xsq);
  74073. this._scaleVector.y = ys * Math.sqrt(ysq);
  74074. this._scaleVector.z = zs * Math.sqrt(zsq);
  74075. if (this._parent) {
  74076. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  74077. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  74078. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  74079. }
  74080. 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);
  74081. };
  74082. /**
  74083. * Get the world direction from an axis that is in the local space of the bone.
  74084. * @param localAxis The local direction that is used to compute the world direction.
  74085. * @param mesh The mesh that this bone is attached to.
  74086. * @returns The world direction
  74087. */
  74088. Bone.prototype.getDirection = function (localAxis, mesh) {
  74089. if (mesh === void 0) { mesh = null; }
  74090. var result = BABYLON.Vector3.Zero();
  74091. this.getDirectionToRef(localAxis, mesh, result);
  74092. return result;
  74093. };
  74094. /**
  74095. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  74096. * @param localAxis The local direction that is used to compute the world direction.
  74097. * @param mesh The mesh that this bone is attached to.
  74098. * @param result The vector3 that the world direction will be copied to.
  74099. */
  74100. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  74101. if (mesh === void 0) { mesh = null; }
  74102. var wm = null;
  74103. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  74104. if (mesh) {
  74105. wm = mesh.getWorldMatrix();
  74106. }
  74107. this._skeleton.computeAbsoluteTransforms();
  74108. var mat = Bone._tmpMats[0];
  74109. mat.copyFrom(this.getAbsoluteTransform());
  74110. if (mesh && wm) {
  74111. mat.multiplyToRef(wm, mat);
  74112. }
  74113. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  74114. result.normalize();
  74115. };
  74116. /**
  74117. * Get the euler rotation of the bone in local or world space.
  74118. * @param space The space that the rotation should be in.
  74119. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74120. * @returns The euler rotation
  74121. */
  74122. Bone.prototype.getRotation = function (space, mesh) {
  74123. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74124. if (mesh === void 0) { mesh = null; }
  74125. var result = BABYLON.Vector3.Zero();
  74126. this.getRotationToRef(space, mesh, result);
  74127. return result;
  74128. };
  74129. /**
  74130. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  74131. * @param space The space that the rotation should be in.
  74132. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74133. * @param result The vector3 that the rotation should be copied to.
  74134. */
  74135. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  74136. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74137. if (mesh === void 0) { mesh = null; }
  74138. var quat = Bone._tmpQuat;
  74139. this.getRotationQuaternionToRef(space, mesh, quat);
  74140. quat.toEulerAnglesToRef(result);
  74141. };
  74142. /**
  74143. * Get the quaternion rotation of the bone in either local or world space.
  74144. * @param space The space that the rotation should be in.
  74145. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74146. * @returns The quaternion rotation
  74147. */
  74148. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  74149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74150. if (mesh === void 0) { mesh = null; }
  74151. var result = BABYLON.Quaternion.Identity();
  74152. this.getRotationQuaternionToRef(space, mesh, result);
  74153. return result;
  74154. };
  74155. /**
  74156. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  74157. * @param space The space that the rotation should be in.
  74158. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74159. * @param result The quaternion that the rotation should be copied to.
  74160. */
  74161. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  74162. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74163. if (mesh === void 0) { mesh = null; }
  74164. if (space == BABYLON.Space.LOCAL) {
  74165. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  74166. }
  74167. else {
  74168. var mat = Bone._tmpMats[0];
  74169. var amat = this.getAbsoluteTransform();
  74170. if (mesh) {
  74171. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  74172. }
  74173. else {
  74174. mat.copyFrom(amat);
  74175. }
  74176. mat.m[0] *= this._scalingDeterminant;
  74177. mat.m[1] *= this._scalingDeterminant;
  74178. mat.m[2] *= this._scalingDeterminant;
  74179. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  74180. }
  74181. };
  74182. /**
  74183. * Get the rotation matrix of the bone in local or world space.
  74184. * @param space The space that the rotation should be in.
  74185. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74186. * @returns The rotation matrix
  74187. */
  74188. Bone.prototype.getRotationMatrix = function (space, mesh) {
  74189. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74190. var result = BABYLON.Matrix.Identity();
  74191. this.getRotationMatrixToRef(space, mesh, result);
  74192. return result;
  74193. };
  74194. /**
  74195. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  74196. * @param space The space that the rotation should be in.
  74197. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  74198. * @param result The quaternion that the rotation should be copied to.
  74199. */
  74200. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  74201. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  74202. if (space == BABYLON.Space.LOCAL) {
  74203. this.getLocalMatrix().getRotationMatrixToRef(result);
  74204. }
  74205. else {
  74206. var mat = Bone._tmpMats[0];
  74207. var amat = this.getAbsoluteTransform();
  74208. if (mesh) {
  74209. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  74210. }
  74211. else {
  74212. mat.copyFrom(amat);
  74213. }
  74214. mat.m[0] *= this._scalingDeterminant;
  74215. mat.m[1] *= this._scalingDeterminant;
  74216. mat.m[2] *= this._scalingDeterminant;
  74217. mat.getRotationMatrixToRef(result);
  74218. }
  74219. };
  74220. /**
  74221. * Get the world position of a point that is in the local space of the bone.
  74222. * @param position The local position
  74223. * @param mesh The mesh that this bone is attached to.
  74224. * @returns The world position
  74225. */
  74226. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  74227. if (mesh === void 0) { mesh = null; }
  74228. var result = BABYLON.Vector3.Zero();
  74229. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  74230. return result;
  74231. };
  74232. /**
  74233. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  74234. * @param position The local position
  74235. * @param mesh The mesh that this bone is attached to.
  74236. * @param result The vector3 that the world position should be copied to.
  74237. */
  74238. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  74239. if (mesh === void 0) { mesh = null; }
  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. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  74255. };
  74256. /**
  74257. * Get the local position of a point that is in world space.
  74258. * @param position The world position
  74259. * @param mesh The mesh that this bone is attached to.
  74260. * @returns The local position
  74261. */
  74262. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  74263. if (mesh === void 0) { mesh = null; }
  74264. var result = BABYLON.Vector3.Zero();
  74265. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  74266. return result;
  74267. };
  74268. /**
  74269. * Get the local position of a point that is in world space and copy it to the result param.
  74270. * @param position The world position
  74271. * @param mesh The mesh that this bone is attached to.
  74272. * @param result The vector3 that the local position should be copied to.
  74273. */
  74274. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  74275. if (mesh === void 0) { mesh = null; }
  74276. var wm = null;
  74277. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  74278. if (mesh) {
  74279. wm = mesh.getWorldMatrix();
  74280. }
  74281. this._skeleton.computeAbsoluteTransforms();
  74282. var tmat = Bone._tmpMats[0];
  74283. tmat.copyFrom(this.getAbsoluteTransform());
  74284. if (mesh && wm) {
  74285. tmat.multiplyToRef(wm, tmat);
  74286. }
  74287. tmat.invert();
  74288. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  74289. };
  74290. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74291. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  74292. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74293. return Bone;
  74294. }(BABYLON.Node));
  74295. BABYLON.Bone = Bone;
  74296. })(BABYLON || (BABYLON = {}));
  74297. //# sourceMappingURL=babylon.bone.js.map
  74298. "use strict";
  74299. var BABYLON;
  74300. (function (BABYLON) {
  74301. var BoneIKController = /** @class */ (function () {
  74302. function BoneIKController(mesh, bone, options) {
  74303. this.targetPosition = BABYLON.Vector3.Zero();
  74304. this.poleTargetPosition = BABYLON.Vector3.Zero();
  74305. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  74306. this.poleAngle = 0;
  74307. this.slerpAmount = 1;
  74308. this._bone1Quat = BABYLON.Quaternion.Identity();
  74309. this._bone1Mat = BABYLON.Matrix.Identity();
  74310. this._bone2Ang = Math.PI;
  74311. this._maxAngle = Math.PI;
  74312. this._rightHandedSystem = false;
  74313. this._bendAxis = BABYLON.Vector3.Right();
  74314. this._slerping = false;
  74315. this._adjustRoll = 0;
  74316. this._bone2 = bone;
  74317. this._bone1 = bone.getParent();
  74318. if (!this._bone1) {
  74319. return;
  74320. }
  74321. this.mesh = mesh;
  74322. var bonePos = bone.getPosition();
  74323. if (bone.getAbsoluteTransform().determinant() > 0) {
  74324. this._rightHandedSystem = true;
  74325. this._bendAxis.x = 0;
  74326. this._bendAxis.y = 0;
  74327. this._bendAxis.z = -1;
  74328. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  74329. this._adjustRoll = Math.PI * .5;
  74330. this._bendAxis.z = 1;
  74331. }
  74332. }
  74333. if (this._bone1.length) {
  74334. var boneScale1 = this._bone1.getScale();
  74335. var boneScale2 = this._bone2.getScale();
  74336. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  74337. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  74338. }
  74339. else if (this._bone1.children[0]) {
  74340. mesh.computeWorldMatrix(true);
  74341. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  74342. var pos2 = this._bone2.getAbsolutePosition(mesh);
  74343. var pos3 = this._bone1.getAbsolutePosition(mesh);
  74344. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  74345. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  74346. }
  74347. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  74348. this.maxAngle = Math.PI;
  74349. if (options) {
  74350. if (options.targetMesh) {
  74351. this.targetMesh = options.targetMesh;
  74352. this.targetMesh.computeWorldMatrix(true);
  74353. }
  74354. if (options.poleTargetMesh) {
  74355. this.poleTargetMesh = options.poleTargetMesh;
  74356. this.poleTargetMesh.computeWorldMatrix(true);
  74357. }
  74358. else if (options.poleTargetBone) {
  74359. this.poleTargetBone = options.poleTargetBone;
  74360. }
  74361. else if (this._bone1.getParent()) {
  74362. this.poleTargetBone = this._bone1.getParent();
  74363. }
  74364. if (options.poleTargetLocalOffset) {
  74365. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  74366. }
  74367. if (options.poleAngle) {
  74368. this.poleAngle = options.poleAngle;
  74369. }
  74370. if (options.bendAxis) {
  74371. this._bendAxis.copyFrom(options.bendAxis);
  74372. }
  74373. if (options.maxAngle) {
  74374. this.maxAngle = options.maxAngle;
  74375. }
  74376. if (options.slerpAmount) {
  74377. this.slerpAmount = options.slerpAmount;
  74378. }
  74379. }
  74380. }
  74381. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  74382. get: function () {
  74383. return this._maxAngle;
  74384. },
  74385. set: function (value) {
  74386. this._setMaxAngle(value);
  74387. },
  74388. enumerable: true,
  74389. configurable: true
  74390. });
  74391. BoneIKController.prototype._setMaxAngle = function (ang) {
  74392. if (ang < 0) {
  74393. ang = 0;
  74394. }
  74395. if (ang > Math.PI || ang == undefined) {
  74396. ang = Math.PI;
  74397. }
  74398. this._maxAngle = ang;
  74399. var a = this._bone1Length;
  74400. var b = this._bone2Length;
  74401. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  74402. };
  74403. BoneIKController.prototype.update = function () {
  74404. var bone1 = this._bone1;
  74405. if (!bone1) {
  74406. return;
  74407. }
  74408. var target = this.targetPosition;
  74409. var poleTarget = this.poleTargetPosition;
  74410. var mat1 = BoneIKController._tmpMats[0];
  74411. var mat2 = BoneIKController._tmpMats[1];
  74412. if (this.targetMesh) {
  74413. target.copyFrom(this.targetMesh.getAbsolutePosition());
  74414. }
  74415. if (this.poleTargetBone) {
  74416. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  74417. }
  74418. else if (this.poleTargetMesh) {
  74419. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  74420. }
  74421. var bonePos = BoneIKController._tmpVecs[0];
  74422. var zaxis = BoneIKController._tmpVecs[1];
  74423. var xaxis = BoneIKController._tmpVecs[2];
  74424. var yaxis = BoneIKController._tmpVecs[3];
  74425. var upAxis = BoneIKController._tmpVecs[4];
  74426. var _tmpQuat = BoneIKController._tmpQuat;
  74427. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  74428. poleTarget.subtractToRef(bonePos, upAxis);
  74429. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  74430. upAxis.y = 1;
  74431. }
  74432. else {
  74433. upAxis.normalize();
  74434. }
  74435. target.subtractToRef(bonePos, yaxis);
  74436. yaxis.normalize();
  74437. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  74438. zaxis.normalize();
  74439. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  74440. xaxis.normalize();
  74441. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  74442. var a = this._bone1Length;
  74443. var b = this._bone2Length;
  74444. var c = BABYLON.Vector3.Distance(bonePos, target);
  74445. if (this._maxReach > 0) {
  74446. c = Math.min(this._maxReach, c);
  74447. }
  74448. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  74449. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  74450. if (acosa > 1) {
  74451. acosa = 1;
  74452. }
  74453. if (acosb > 1) {
  74454. acosb = 1;
  74455. }
  74456. if (acosa < -1) {
  74457. acosa = -1;
  74458. }
  74459. if (acosb < -1) {
  74460. acosb = -1;
  74461. }
  74462. var angA = Math.acos(acosa);
  74463. var angB = Math.acos(acosb);
  74464. var angC = -angA - angB;
  74465. if (this._rightHandedSystem) {
  74466. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  74467. mat2.multiplyToRef(mat1, mat1);
  74468. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  74469. mat2.multiplyToRef(mat1, mat1);
  74470. }
  74471. else {
  74472. var _tmpVec = BoneIKController._tmpVecs[5];
  74473. _tmpVec.copyFrom(this._bendAxis);
  74474. _tmpVec.x *= -1;
  74475. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  74476. mat2.multiplyToRef(mat1, mat1);
  74477. }
  74478. if (this.poleAngle) {
  74479. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  74480. mat1.multiplyToRef(mat2, mat1);
  74481. }
  74482. if (this._bone1) {
  74483. if (this.slerpAmount < 1) {
  74484. if (!this._slerping) {
  74485. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  74486. }
  74487. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  74488. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  74489. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  74490. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  74491. this._slerping = true;
  74492. }
  74493. else {
  74494. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  74495. this._bone1Mat.copyFrom(mat1);
  74496. this._slerping = false;
  74497. }
  74498. }
  74499. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  74500. this._bone2Ang = angC;
  74501. };
  74502. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74503. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  74504. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74505. return BoneIKController;
  74506. }());
  74507. BABYLON.BoneIKController = BoneIKController;
  74508. })(BABYLON || (BABYLON = {}));
  74509. //# sourceMappingURL=babylon.boneIKController.js.map
  74510. "use strict";
  74511. var BABYLON;
  74512. (function (BABYLON) {
  74513. var BoneLookController = /** @class */ (function () {
  74514. /**
  74515. * Create a BoneLookController
  74516. * @param mesh the mesh that the bone belongs to
  74517. * @param bone the bone that will be looking to the target
  74518. * @param target the target Vector3 to look at
  74519. * @param settings optional settings:
  74520. * - maxYaw: the maximum angle the bone will yaw to
  74521. * - minYaw: the minimum angle the bone will yaw to
  74522. * - maxPitch: the maximum angle the bone will pitch to
  74523. * - minPitch: the minimum angle the bone will yaw to
  74524. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  74525. * - upAxis: the up axis of the coordinate system
  74526. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  74527. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  74528. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  74529. * - adjustYaw: used to make an adjustment to the yaw of the bone
  74530. * - adjustPitch: used to make an adjustment to the pitch of the bone
  74531. * - adjustRoll: used to make an adjustment to the roll of the bone
  74532. **/
  74533. function BoneLookController(mesh, bone, target, options) {
  74534. /**
  74535. * The up axis of the coordinate system that is used when the bone is rotated.
  74536. */
  74537. this.upAxis = BABYLON.Vector3.Up();
  74538. /**
  74539. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  74540. */
  74541. this.upAxisSpace = BABYLON.Space.LOCAL;
  74542. /**
  74543. * Used to make an adjustment to the yaw of the bone.
  74544. */
  74545. this.adjustYaw = 0;
  74546. /**
  74547. * Used to make an adjustment to the pitch of the bone.
  74548. */
  74549. this.adjustPitch = 0;
  74550. /**
  74551. * Used to make an adjustment to the roll of the bone.
  74552. */
  74553. this.adjustRoll = 0;
  74554. /**
  74555. * 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).
  74556. */
  74557. this.slerpAmount = 1;
  74558. this._boneQuat = BABYLON.Quaternion.Identity();
  74559. this._slerping = false;
  74560. this._firstFrameSkipped = false;
  74561. this._fowardAxis = BABYLON.Vector3.Forward();
  74562. this.mesh = mesh;
  74563. this.bone = bone;
  74564. this.target = target;
  74565. if (options) {
  74566. if (options.adjustYaw) {
  74567. this.adjustYaw = options.adjustYaw;
  74568. }
  74569. if (options.adjustPitch) {
  74570. this.adjustPitch = options.adjustPitch;
  74571. }
  74572. if (options.adjustRoll) {
  74573. this.adjustRoll = options.adjustRoll;
  74574. }
  74575. if (options.maxYaw != null) {
  74576. this.maxYaw = options.maxYaw;
  74577. }
  74578. else {
  74579. this.maxYaw = Math.PI;
  74580. }
  74581. if (options.minYaw != null) {
  74582. this.minYaw = options.minYaw;
  74583. }
  74584. else {
  74585. this.minYaw = -Math.PI;
  74586. }
  74587. if (options.maxPitch != null) {
  74588. this.maxPitch = options.maxPitch;
  74589. }
  74590. else {
  74591. this.maxPitch = Math.PI;
  74592. }
  74593. if (options.minPitch != null) {
  74594. this.minPitch = options.minPitch;
  74595. }
  74596. else {
  74597. this.minPitch = -Math.PI;
  74598. }
  74599. if (options.slerpAmount != null) {
  74600. this.slerpAmount = options.slerpAmount;
  74601. }
  74602. if (options.upAxis != null) {
  74603. this.upAxis = options.upAxis;
  74604. }
  74605. if (options.upAxisSpace != null) {
  74606. this.upAxisSpace = options.upAxisSpace;
  74607. }
  74608. if (options.yawAxis != null || options.pitchAxis != null) {
  74609. var newYawAxis = BABYLON.Axis.Y;
  74610. var newPitchAxis = BABYLON.Axis.X;
  74611. if (options.yawAxis != null) {
  74612. newYawAxis = options.yawAxis.clone();
  74613. newYawAxis.normalize();
  74614. }
  74615. if (options.pitchAxis != null) {
  74616. newPitchAxis = options.pitchAxis.clone();
  74617. newPitchAxis.normalize();
  74618. }
  74619. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  74620. this._transformYawPitch = BABYLON.Matrix.Identity();
  74621. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  74622. this._transformYawPitchInv = this._transformYawPitch.clone();
  74623. this._transformYawPitch.invert();
  74624. }
  74625. }
  74626. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  74627. this.upAxisSpace = BABYLON.Space.LOCAL;
  74628. }
  74629. }
  74630. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  74631. /**
  74632. * Get/set the minimum yaw angle that the bone can look to.
  74633. */
  74634. get: function () {
  74635. return this._minYaw;
  74636. },
  74637. set: function (value) {
  74638. this._minYaw = value;
  74639. this._minYawSin = Math.sin(value);
  74640. this._minYawCos = Math.cos(value);
  74641. if (this._maxYaw != null) {
  74642. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  74643. this._yawRange = this._maxYaw - this._minYaw;
  74644. }
  74645. },
  74646. enumerable: true,
  74647. configurable: true
  74648. });
  74649. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  74650. /**
  74651. * Get/set the maximum yaw angle that the bone can look to.
  74652. */
  74653. get: function () {
  74654. return this._maxYaw;
  74655. },
  74656. set: function (value) {
  74657. this._maxYaw = value;
  74658. this._maxYawSin = Math.sin(value);
  74659. this._maxYawCos = Math.cos(value);
  74660. if (this._minYaw != null) {
  74661. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  74662. this._yawRange = this._maxYaw - this._minYaw;
  74663. }
  74664. },
  74665. enumerable: true,
  74666. configurable: true
  74667. });
  74668. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  74669. /**
  74670. * Get/set the minimum pitch angle that the bone can look to.
  74671. */
  74672. get: function () {
  74673. return this._minPitch;
  74674. },
  74675. set: function (value) {
  74676. this._minPitch = value;
  74677. this._minPitchTan = Math.tan(value);
  74678. },
  74679. enumerable: true,
  74680. configurable: true
  74681. });
  74682. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  74683. /**
  74684. * Get/set the maximum pitch angle that the bone can look to.
  74685. */
  74686. get: function () {
  74687. return this._maxPitch;
  74688. },
  74689. set: function (value) {
  74690. this._maxPitch = value;
  74691. this._maxPitchTan = Math.tan(value);
  74692. },
  74693. enumerable: true,
  74694. configurable: true
  74695. });
  74696. /**
  74697. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  74698. */
  74699. BoneLookController.prototype.update = function () {
  74700. //skip the first frame when slerping so that the mesh rotation is correct
  74701. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  74702. this._firstFrameSkipped = true;
  74703. return;
  74704. }
  74705. var bone = this.bone;
  74706. var bonePos = BoneLookController._tmpVecs[0];
  74707. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  74708. var target = this.target;
  74709. var _tmpMat1 = BoneLookController._tmpMats[0];
  74710. var _tmpMat2 = BoneLookController._tmpMats[1];
  74711. var mesh = this.mesh;
  74712. var parentBone = bone.getParent();
  74713. var upAxis = BoneLookController._tmpVecs[1];
  74714. upAxis.copyFrom(this.upAxis);
  74715. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  74716. if (this._transformYawPitch) {
  74717. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  74718. }
  74719. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  74720. }
  74721. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  74722. mesh.getDirectionToRef(upAxis, upAxis);
  74723. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  74724. upAxis.normalize();
  74725. }
  74726. }
  74727. var checkYaw = false;
  74728. var checkPitch = false;
  74729. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  74730. checkYaw = true;
  74731. }
  74732. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  74733. checkPitch = true;
  74734. }
  74735. if (checkYaw || checkPitch) {
  74736. var spaceMat = BoneLookController._tmpMats[2];
  74737. var spaceMatInv = BoneLookController._tmpMats[3];
  74738. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  74739. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  74740. }
  74741. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  74742. spaceMat.copyFrom(mesh.getWorldMatrix());
  74743. }
  74744. else {
  74745. var forwardAxis = BoneLookController._tmpVecs[2];
  74746. forwardAxis.copyFrom(this._fowardAxis);
  74747. if (this._transformYawPitch) {
  74748. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  74749. }
  74750. if (parentBone) {
  74751. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  74752. }
  74753. else {
  74754. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  74755. }
  74756. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  74757. rightAxis.normalize();
  74758. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  74759. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  74760. }
  74761. spaceMat.invertToRef(spaceMatInv);
  74762. var xzlen = null;
  74763. if (checkPitch) {
  74764. var localTarget = BoneLookController._tmpVecs[3];
  74765. target.subtractToRef(bonePos, localTarget);
  74766. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74767. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74768. var pitch = Math.atan2(localTarget.y, xzlen);
  74769. var newPitch = pitch;
  74770. if (pitch > this._maxPitch) {
  74771. localTarget.y = this._maxPitchTan * xzlen;
  74772. newPitch = this._maxPitch;
  74773. }
  74774. else if (pitch < this._minPitch) {
  74775. localTarget.y = this._minPitchTan * xzlen;
  74776. newPitch = this._minPitch;
  74777. }
  74778. if (pitch != newPitch) {
  74779. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74780. localTarget.addInPlace(bonePos);
  74781. target = localTarget;
  74782. }
  74783. }
  74784. if (checkYaw) {
  74785. var localTarget = BoneLookController._tmpVecs[4];
  74786. target.subtractToRef(bonePos, localTarget);
  74787. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74788. var yaw = Math.atan2(localTarget.x, localTarget.z);
  74789. var newYaw = yaw;
  74790. if (yaw > this._maxYaw || yaw < this._minYaw) {
  74791. if (xzlen == null) {
  74792. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74793. }
  74794. if (this._yawRange > Math.PI) {
  74795. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  74796. localTarget.z = this._maxYawCos * xzlen;
  74797. localTarget.x = this._maxYawSin * xzlen;
  74798. newYaw = this._maxYaw;
  74799. }
  74800. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  74801. localTarget.z = this._minYawCos * xzlen;
  74802. localTarget.x = this._minYawSin * xzlen;
  74803. newYaw = this._minYaw;
  74804. }
  74805. }
  74806. else {
  74807. if (yaw > this._maxYaw) {
  74808. localTarget.z = this._maxYawCos * xzlen;
  74809. localTarget.x = this._maxYawSin * xzlen;
  74810. newYaw = this._maxYaw;
  74811. }
  74812. else if (yaw < this._minYaw) {
  74813. localTarget.z = this._minYawCos * xzlen;
  74814. localTarget.x = this._minYawSin * xzlen;
  74815. newYaw = this._minYaw;
  74816. }
  74817. }
  74818. }
  74819. if (this._slerping && this._yawRange > Math.PI) {
  74820. //are we going to be crossing into the min/max region?
  74821. var boneFwd = BoneLookController._tmpVecs[8];
  74822. boneFwd.copyFrom(BABYLON.Axis.Z);
  74823. if (this._transformYawPitch) {
  74824. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  74825. }
  74826. var boneRotMat = BoneLookController._tmpMats[4];
  74827. this._boneQuat.toRotationMatrix(boneRotMat);
  74828. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  74829. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  74830. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  74831. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  74832. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  74833. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  74834. if (angBtwTar > angBtwMidYaw) {
  74835. if (xzlen == null) {
  74836. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74837. }
  74838. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  74839. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  74840. if (angBtwMin < angBtwMax) {
  74841. newYaw = boneYaw + Math.PI * .75;
  74842. localTarget.z = Math.cos(newYaw) * xzlen;
  74843. localTarget.x = Math.sin(newYaw) * xzlen;
  74844. }
  74845. else {
  74846. newYaw = boneYaw - Math.PI * .75;
  74847. localTarget.z = Math.cos(newYaw) * xzlen;
  74848. localTarget.x = Math.sin(newYaw) * xzlen;
  74849. }
  74850. }
  74851. }
  74852. if (yaw != newYaw) {
  74853. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74854. localTarget.addInPlace(bonePos);
  74855. target = localTarget;
  74856. }
  74857. }
  74858. }
  74859. var zaxis = BoneLookController._tmpVecs[5];
  74860. var xaxis = BoneLookController._tmpVecs[6];
  74861. var yaxis = BoneLookController._tmpVecs[7];
  74862. var _tmpQuat = BoneLookController._tmpQuat;
  74863. target.subtractToRef(bonePos, zaxis);
  74864. zaxis.normalize();
  74865. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  74866. xaxis.normalize();
  74867. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  74868. yaxis.normalize();
  74869. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  74870. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  74871. return;
  74872. }
  74873. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  74874. return;
  74875. }
  74876. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  74877. return;
  74878. }
  74879. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  74880. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74881. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74882. }
  74883. if (this.slerpAmount < 1) {
  74884. if (!this._slerping) {
  74885. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74886. }
  74887. if (this._transformYawPitch) {
  74888. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74889. }
  74890. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74891. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74892. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74893. this._slerping = true;
  74894. }
  74895. else {
  74896. if (this._transformYawPitch) {
  74897. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74898. }
  74899. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74900. this._slerping = false;
  74901. }
  74902. };
  74903. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74904. var angDiff = ang2 - ang1;
  74905. angDiff %= Math.PI * 2;
  74906. if (angDiff > Math.PI) {
  74907. angDiff -= Math.PI * 2;
  74908. }
  74909. else if (angDiff < -Math.PI) {
  74910. angDiff += Math.PI * 2;
  74911. }
  74912. return angDiff;
  74913. };
  74914. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74915. ang1 %= (2 * Math.PI);
  74916. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74917. ang2 %= (2 * Math.PI);
  74918. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74919. var ab = 0;
  74920. if (ang1 < ang2) {
  74921. ab = ang2 - ang1;
  74922. }
  74923. else {
  74924. ab = ang1 - ang2;
  74925. }
  74926. if (ab > Math.PI) {
  74927. ab = Math.PI * 2 - ab;
  74928. }
  74929. return ab;
  74930. };
  74931. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74932. ang %= (2 * Math.PI);
  74933. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74934. ang1 %= (2 * Math.PI);
  74935. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74936. ang2 %= (2 * Math.PI);
  74937. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74938. if (ang1 < ang2) {
  74939. if (ang > ang1 && ang < ang2) {
  74940. return true;
  74941. }
  74942. }
  74943. else {
  74944. if (ang > ang2 && ang < ang1) {
  74945. return true;
  74946. }
  74947. }
  74948. return false;
  74949. };
  74950. 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()];
  74951. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74952. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74953. return BoneLookController;
  74954. }());
  74955. BABYLON.BoneLookController = BoneLookController;
  74956. })(BABYLON || (BABYLON = {}));
  74957. //# sourceMappingURL=babylon.boneLookController.js.map
  74958. "use strict";
  74959. var BABYLON;
  74960. (function (BABYLON) {
  74961. var Skeleton = /** @class */ (function () {
  74962. function Skeleton(name, id, scene) {
  74963. this.name = name;
  74964. this.id = id;
  74965. this.bones = new Array();
  74966. this.needInitialSkinMatrix = false;
  74967. this._isDirty = true;
  74968. this._meshesWithPoseMatrix = new Array();
  74969. this._identity = BABYLON.Matrix.Identity();
  74970. this._ranges = {};
  74971. this._lastAbsoluteTransformsUpdateId = -1;
  74972. /**
  74973. * Specifies if the skeleton should be serialized.
  74974. */
  74975. this.doNotSerialize = false;
  74976. // Events
  74977. /**
  74978. * An event triggered before computing the skeleton's matrices
  74979. */
  74980. this.onBeforeComputeObservable = new BABYLON.Observable();
  74981. this.bones = [];
  74982. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74983. scene.skeletons.push(this);
  74984. //make sure it will recalculate the matrix next time prepare is called.
  74985. this._isDirty = true;
  74986. }
  74987. // Members
  74988. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74989. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74990. return mesh._bonesTransformMatrices;
  74991. }
  74992. if (!this._transformMatrices) {
  74993. this.prepare();
  74994. }
  74995. return this._transformMatrices;
  74996. };
  74997. Skeleton.prototype.getScene = function () {
  74998. return this._scene;
  74999. };
  75000. // Methods
  75001. /**
  75002. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  75003. */
  75004. Skeleton.prototype.toString = function (fullDetails) {
  75005. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  75006. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  75007. if (fullDetails) {
  75008. ret += ", Ranges: {";
  75009. var first = true;
  75010. for (var name_1 in this._ranges) {
  75011. if (first) {
  75012. ret += ", ";
  75013. first = false;
  75014. }
  75015. ret += name_1;
  75016. }
  75017. ret += "}";
  75018. }
  75019. return ret;
  75020. };
  75021. /**
  75022. * Get bone's index searching by name
  75023. * @param {string} name is bone's name to search for
  75024. * @return {number} Indice of the bone. Returns -1 if not found
  75025. */
  75026. Skeleton.prototype.getBoneIndexByName = function (name) {
  75027. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  75028. if (this.bones[boneIndex].name === name) {
  75029. return boneIndex;
  75030. }
  75031. }
  75032. return -1;
  75033. };
  75034. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  75035. // check name not already in use
  75036. if (!this._ranges[name]) {
  75037. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  75038. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  75039. if (this.bones[i].animations[0]) {
  75040. this.bones[i].animations[0].createRange(name, from, to);
  75041. }
  75042. }
  75043. }
  75044. };
  75045. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  75046. if (deleteFrames === void 0) { deleteFrames = true; }
  75047. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  75048. if (this.bones[i].animations[0]) {
  75049. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  75050. }
  75051. }
  75052. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  75053. };
  75054. Skeleton.prototype.getAnimationRange = function (name) {
  75055. return this._ranges[name];
  75056. };
  75057. /**
  75058. * Returns as an Array, all AnimationRanges defined on this skeleton
  75059. */
  75060. Skeleton.prototype.getAnimationRanges = function () {
  75061. var animationRanges = [];
  75062. var name;
  75063. var i = 0;
  75064. for (name in this._ranges) {
  75065. animationRanges[i] = this._ranges[name];
  75066. i++;
  75067. }
  75068. return animationRanges;
  75069. };
  75070. /**
  75071. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  75072. */
  75073. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  75074. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  75075. if (this._ranges[name] || !source.getAnimationRange(name)) {
  75076. return false;
  75077. }
  75078. var ret = true;
  75079. var frameOffset = this._getHighestAnimationFrame() + 1;
  75080. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  75081. var boneDict = {};
  75082. var sourceBones = source.bones;
  75083. var nBones;
  75084. var i;
  75085. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  75086. boneDict[sourceBones[i].name] = sourceBones[i];
  75087. }
  75088. if (this.bones.length !== sourceBones.length) {
  75089. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  75090. ret = false;
  75091. }
  75092. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  75093. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  75094. var boneName = this.bones[i].name;
  75095. var sourceBone = boneDict[boneName];
  75096. if (sourceBone) {
  75097. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  75098. }
  75099. else {
  75100. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  75101. ret = false;
  75102. }
  75103. }
  75104. // do not call createAnimationRange(), since it also is done to bones, which was already done
  75105. var range = source.getAnimationRange(name);
  75106. if (range) {
  75107. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  75108. }
  75109. return ret;
  75110. };
  75111. Skeleton.prototype.returnToRest = function () {
  75112. for (var index = 0; index < this.bones.length; index++) {
  75113. this.bones[index].returnToRest();
  75114. }
  75115. };
  75116. Skeleton.prototype._getHighestAnimationFrame = function () {
  75117. var ret = 0;
  75118. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  75119. if (this.bones[i].animations[0]) {
  75120. var highest = this.bones[i].animations[0].getHighestFrame();
  75121. if (ret < highest) {
  75122. ret = highest;
  75123. }
  75124. }
  75125. }
  75126. return ret;
  75127. };
  75128. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  75129. var range = this.getAnimationRange(name);
  75130. if (!range) {
  75131. return null;
  75132. }
  75133. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  75134. };
  75135. Skeleton.prototype._markAsDirty = function () {
  75136. this._isDirty = true;
  75137. };
  75138. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  75139. this._meshesWithPoseMatrix.push(mesh);
  75140. };
  75141. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  75142. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  75143. if (index > -1) {
  75144. this._meshesWithPoseMatrix.splice(index, 1);
  75145. }
  75146. };
  75147. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  75148. this.onBeforeComputeObservable.notifyObservers(this);
  75149. for (var index = 0; index < this.bones.length; index++) {
  75150. var bone = this.bones[index];
  75151. var parentBone = bone.getParent();
  75152. if (parentBone) {
  75153. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  75154. }
  75155. else {
  75156. if (initialSkinMatrix) {
  75157. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  75158. }
  75159. else {
  75160. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  75161. }
  75162. }
  75163. if (bone._index !== -1) {
  75164. var mappedIndex = bone._index === null ? index : bone._index;
  75165. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  75166. }
  75167. }
  75168. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  75169. };
  75170. Skeleton.prototype.prepare = function () {
  75171. if (!this._isDirty) {
  75172. return;
  75173. }
  75174. if (this.needInitialSkinMatrix) {
  75175. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  75176. var mesh = this._meshesWithPoseMatrix[index];
  75177. var poseMatrix = mesh.getPoseMatrix();
  75178. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  75179. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  75180. }
  75181. if (this._synchronizedWithMesh !== mesh) {
  75182. this._synchronizedWithMesh = mesh;
  75183. // Prepare bones
  75184. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  75185. var bone = this.bones[boneIndex];
  75186. if (!bone.getParent()) {
  75187. var matrix = bone.getBaseMatrix();
  75188. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  75189. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  75190. }
  75191. }
  75192. }
  75193. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  75194. }
  75195. }
  75196. else {
  75197. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  75198. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  75199. }
  75200. this._computeTransformMatrices(this._transformMatrices, null);
  75201. }
  75202. this._isDirty = false;
  75203. this._scene._activeBones.addCount(this.bones.length, false);
  75204. };
  75205. Skeleton.prototype.getAnimatables = function () {
  75206. if (!this._animatables || this._animatables.length !== this.bones.length) {
  75207. this._animatables = [];
  75208. for (var index = 0; index < this.bones.length; index++) {
  75209. this._animatables.push(this.bones[index]);
  75210. }
  75211. }
  75212. return this._animatables;
  75213. };
  75214. Skeleton.prototype.clone = function (name, id) {
  75215. var result = new Skeleton(name, id || name, this._scene);
  75216. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  75217. for (var index = 0; index < this.bones.length; index++) {
  75218. var source = this.bones[index];
  75219. var parentBone = null;
  75220. var parent_1 = source.getParent();
  75221. if (parent_1) {
  75222. var parentIndex = this.bones.indexOf(parent_1);
  75223. parentBone = result.bones[parentIndex];
  75224. }
  75225. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  75226. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  75227. }
  75228. if (this._ranges) {
  75229. result._ranges = {};
  75230. for (var rangeName in this._ranges) {
  75231. var range = this._ranges[rangeName];
  75232. if (range) {
  75233. result._ranges[rangeName] = range.clone();
  75234. }
  75235. }
  75236. }
  75237. this._isDirty = true;
  75238. return result;
  75239. };
  75240. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  75241. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  75242. this.bones.forEach(function (bone) {
  75243. bone.animations.forEach(function (animation) {
  75244. animation.enableBlending = true;
  75245. animation.blendingSpeed = blendingSpeed;
  75246. });
  75247. });
  75248. };
  75249. Skeleton.prototype.dispose = function () {
  75250. this._meshesWithPoseMatrix = [];
  75251. // Animations
  75252. this.getScene().stopAnimation(this);
  75253. // Remove from scene
  75254. this.getScene().removeSkeleton(this);
  75255. };
  75256. Skeleton.prototype.serialize = function () {
  75257. var serializationObject = {};
  75258. serializationObject.name = this.name;
  75259. serializationObject.id = this.id;
  75260. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  75261. serializationObject.bones = [];
  75262. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  75263. for (var index = 0; index < this.bones.length; index++) {
  75264. var bone = this.bones[index];
  75265. var parent_2 = bone.getParent();
  75266. var serializedBone = {
  75267. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  75268. name: bone.name,
  75269. matrix: bone.getBaseMatrix().toArray(),
  75270. rest: bone.getRestPose().toArray()
  75271. };
  75272. serializationObject.bones.push(serializedBone);
  75273. if (bone.length) {
  75274. serializedBone.length = bone.length;
  75275. }
  75276. if (bone.animations && bone.animations.length > 0) {
  75277. serializedBone.animation = bone.animations[0].serialize();
  75278. }
  75279. serializationObject.ranges = [];
  75280. for (var name in this._ranges) {
  75281. var source = this._ranges[name];
  75282. if (!source) {
  75283. continue;
  75284. }
  75285. var range = {};
  75286. range.name = name;
  75287. range.from = source.from;
  75288. range.to = source.to;
  75289. serializationObject.ranges.push(range);
  75290. }
  75291. }
  75292. return serializationObject;
  75293. };
  75294. Skeleton.Parse = function (parsedSkeleton, scene) {
  75295. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  75296. if (parsedSkeleton.dimensionsAtRest) {
  75297. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  75298. }
  75299. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  75300. var index;
  75301. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  75302. var parsedBone = parsedSkeleton.bones[index];
  75303. var parentBone = null;
  75304. if (parsedBone.parentBoneIndex > -1) {
  75305. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  75306. }
  75307. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  75308. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  75309. if (parsedBone.length) {
  75310. bone.length = parsedBone.length;
  75311. }
  75312. if (parsedBone.animation) {
  75313. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  75314. }
  75315. }
  75316. // placed after bones, so createAnimationRange can cascade down
  75317. if (parsedSkeleton.ranges) {
  75318. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  75319. var data = parsedSkeleton.ranges[index];
  75320. skeleton.createAnimationRange(data.name, data.from, data.to);
  75321. }
  75322. }
  75323. return skeleton;
  75324. };
  75325. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  75326. if (forceUpdate === void 0) { forceUpdate = false; }
  75327. var renderId = this._scene.getRenderId();
  75328. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  75329. this.bones[0].computeAbsoluteTransforms();
  75330. this._lastAbsoluteTransformsUpdateId = renderId;
  75331. }
  75332. };
  75333. Skeleton.prototype.getPoseMatrix = function () {
  75334. var poseMatrix = null;
  75335. if (this._meshesWithPoseMatrix.length > 0) {
  75336. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  75337. }
  75338. return poseMatrix;
  75339. };
  75340. Skeleton.prototype.sortBones = function () {
  75341. var bones = new Array();
  75342. var visited = new Array(this.bones.length);
  75343. for (var index = 0; index < this.bones.length; index++) {
  75344. this._sortBones(index, bones, visited);
  75345. }
  75346. this.bones = bones;
  75347. };
  75348. Skeleton.prototype._sortBones = function (index, bones, visited) {
  75349. if (visited[index]) {
  75350. return;
  75351. }
  75352. visited[index] = true;
  75353. var bone = this.bones[index];
  75354. if (bone._index === undefined) {
  75355. bone._index = index;
  75356. }
  75357. var parentBone = bone.getParent();
  75358. if (parentBone) {
  75359. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  75360. }
  75361. bones.push(bone);
  75362. };
  75363. return Skeleton;
  75364. }());
  75365. BABYLON.Skeleton = Skeleton;
  75366. })(BABYLON || (BABYLON = {}));
  75367. //# sourceMappingURL=babylon.skeleton.js.map
  75368. "use strict";
  75369. var BABYLON;
  75370. (function (BABYLON) {
  75371. var SphericalPolynomial = /** @class */ (function () {
  75372. function SphericalPolynomial() {
  75373. this.x = BABYLON.Vector3.Zero();
  75374. this.y = BABYLON.Vector3.Zero();
  75375. this.z = BABYLON.Vector3.Zero();
  75376. this.xx = BABYLON.Vector3.Zero();
  75377. this.yy = BABYLON.Vector3.Zero();
  75378. this.zz = BABYLON.Vector3.Zero();
  75379. this.xy = BABYLON.Vector3.Zero();
  75380. this.yz = BABYLON.Vector3.Zero();
  75381. this.zx = BABYLON.Vector3.Zero();
  75382. }
  75383. SphericalPolynomial.prototype.addAmbient = function (color) {
  75384. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  75385. this.xx = this.xx.add(colorVector);
  75386. this.yy = this.yy.add(colorVector);
  75387. this.zz = this.zz.add(colorVector);
  75388. };
  75389. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  75390. var result = new SphericalPolynomial();
  75391. result.x = harmonics.L11.scale(1.02333);
  75392. result.y = harmonics.L1_1.scale(1.02333);
  75393. result.z = harmonics.L10.scale(1.02333);
  75394. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  75395. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  75396. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  75397. result.yz = harmonics.L2_1.scale(0.858086);
  75398. result.zx = harmonics.L21.scale(0.858086);
  75399. result.xy = harmonics.L2_2.scale(0.858086);
  75400. result.scale(1.0 / Math.PI);
  75401. return result;
  75402. };
  75403. SphericalPolynomial.prototype.scale = function (scale) {
  75404. this.x = this.x.scale(scale);
  75405. this.y = this.y.scale(scale);
  75406. this.z = this.z.scale(scale);
  75407. this.xx = this.xx.scale(scale);
  75408. this.yy = this.yy.scale(scale);
  75409. this.zz = this.zz.scale(scale);
  75410. this.yz = this.yz.scale(scale);
  75411. this.zx = this.zx.scale(scale);
  75412. this.xy = this.xy.scale(scale);
  75413. };
  75414. return SphericalPolynomial;
  75415. }());
  75416. BABYLON.SphericalPolynomial = SphericalPolynomial;
  75417. var SphericalHarmonics = /** @class */ (function () {
  75418. function SphericalHarmonics() {
  75419. this.L00 = BABYLON.Vector3.Zero();
  75420. this.L1_1 = BABYLON.Vector3.Zero();
  75421. this.L10 = BABYLON.Vector3.Zero();
  75422. this.L11 = BABYLON.Vector3.Zero();
  75423. this.L2_2 = BABYLON.Vector3.Zero();
  75424. this.L2_1 = BABYLON.Vector3.Zero();
  75425. this.L20 = BABYLON.Vector3.Zero();
  75426. this.L21 = BABYLON.Vector3.Zero();
  75427. this.L22 = BABYLON.Vector3.Zero();
  75428. }
  75429. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  75430. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  75431. var c = colorVector.scale(deltaSolidAngle);
  75432. this.L00 = this.L00.add(c.scale(0.282095));
  75433. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  75434. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  75435. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  75436. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  75437. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  75438. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  75439. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  75440. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  75441. };
  75442. SphericalHarmonics.prototype.scale = function (scale) {
  75443. this.L00 = this.L00.scale(scale);
  75444. this.L1_1 = this.L1_1.scale(scale);
  75445. this.L10 = this.L10.scale(scale);
  75446. this.L11 = this.L11.scale(scale);
  75447. this.L2_2 = this.L2_2.scale(scale);
  75448. this.L2_1 = this.L2_1.scale(scale);
  75449. this.L20 = this.L20.scale(scale);
  75450. this.L21 = this.L21.scale(scale);
  75451. this.L22 = this.L22.scale(scale);
  75452. };
  75453. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  75454. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  75455. //
  75456. // E_lm = A_l * L_lm
  75457. //
  75458. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  75459. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  75460. // the scaling factors are given in equation 9.
  75461. // Constant (Band 0)
  75462. this.L00 = this.L00.scale(3.141593);
  75463. // Linear (Band 1)
  75464. this.L1_1 = this.L1_1.scale(2.094395);
  75465. this.L10 = this.L10.scale(2.094395);
  75466. this.L11 = this.L11.scale(2.094395);
  75467. // Quadratic (Band 2)
  75468. this.L2_2 = this.L2_2.scale(0.785398);
  75469. this.L2_1 = this.L2_1.scale(0.785398);
  75470. this.L20 = this.L20.scale(0.785398);
  75471. this.L21 = this.L21.scale(0.785398);
  75472. this.L22 = this.L22.scale(0.785398);
  75473. };
  75474. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  75475. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  75476. // L = (1/pi) * E * rho
  75477. //
  75478. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  75479. this.scale(1.0 / Math.PI);
  75480. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  75481. // (The pixel shader must apply albedo after texture fetches, etc).
  75482. };
  75483. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  75484. var result = new SphericalHarmonics();
  75485. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  75486. result.L1_1 = polynomial.y.scale(0.977204);
  75487. result.L10 = polynomial.z.scale(0.977204);
  75488. result.L11 = polynomial.x.scale(0.977204);
  75489. result.L2_2 = polynomial.xy.scale(1.16538);
  75490. result.L2_1 = polynomial.yz.scale(1.16538);
  75491. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  75492. result.L21 = polynomial.zx.scale(1.16538);
  75493. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  75494. result.scale(Math.PI);
  75495. return result;
  75496. };
  75497. return SphericalHarmonics;
  75498. }());
  75499. BABYLON.SphericalHarmonics = SphericalHarmonics;
  75500. })(BABYLON || (BABYLON = {}));
  75501. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  75502. "use strict";
  75503. var BABYLON;
  75504. (function (BABYLON) {
  75505. var FileFaceOrientation = /** @class */ (function () {
  75506. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  75507. this.name = name;
  75508. this.worldAxisForNormal = worldAxisForNormal;
  75509. this.worldAxisForFileX = worldAxisForFileX;
  75510. this.worldAxisForFileY = worldAxisForFileY;
  75511. }
  75512. return FileFaceOrientation;
  75513. }());
  75514. ;
  75515. /**
  75516. * Helper class dealing with the extraction of spherical polynomial dataArray
  75517. * from a cube map.
  75518. */
  75519. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  75520. function CubeMapToSphericalPolynomialTools() {
  75521. }
  75522. /**
  75523. * Converts a texture to the according Spherical Polynomial data.
  75524. * This extracts the first 3 orders only as they are the only one used in the lighting.
  75525. *
  75526. * @param texture The texture to extract the information from.
  75527. * @return The Spherical Polynomial data.
  75528. */
  75529. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  75530. if (!texture.isCube) {
  75531. // Only supports cube Textures currently.
  75532. return null;
  75533. }
  75534. var size = texture.getSize().width;
  75535. var right = texture.readPixels(0);
  75536. var left = texture.readPixels(1);
  75537. var up;
  75538. var down;
  75539. if (texture.isRenderTarget) {
  75540. up = texture.readPixels(3);
  75541. down = texture.readPixels(2);
  75542. }
  75543. else {
  75544. up = texture.readPixels(2);
  75545. down = texture.readPixels(3);
  75546. }
  75547. var front = texture.readPixels(4);
  75548. var back = texture.readPixels(5);
  75549. var gammaSpace = texture.gammaSpace;
  75550. // Always read as RGBA.
  75551. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  75552. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75553. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75554. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75555. }
  75556. var cubeInfo = {
  75557. size: size,
  75558. right: right,
  75559. left: left,
  75560. up: up,
  75561. down: down,
  75562. front: front,
  75563. back: back,
  75564. format: format,
  75565. type: type,
  75566. gammaSpace: gammaSpace,
  75567. };
  75568. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  75569. };
  75570. /**
  75571. * Converts a cubemap to the according Spherical Polynomial data.
  75572. * This extracts the first 3 orders only as they are the only one used in the lighting.
  75573. *
  75574. * @param cubeInfo The Cube map to extract the information from.
  75575. * @return The Spherical Polynomial data.
  75576. */
  75577. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  75578. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  75579. var totalSolidAngle = 0.0;
  75580. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  75581. var du = 2.0 / cubeInfo.size;
  75582. var dv = du;
  75583. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  75584. var minUV = du * 0.5 - 1.0;
  75585. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75586. var fileFace = this.FileFaces[faceIndex];
  75587. var dataArray = cubeInfo[fileFace.name];
  75588. var v = minUV;
  75589. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  75590. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  75591. // Because SP is still linear, so summation is fine in that basis.
  75592. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  75593. for (var y = 0; y < cubeInfo.size; y++) {
  75594. var u = minUV;
  75595. for (var x = 0; x < cubeInfo.size; x++) {
  75596. // World direction (not normalised)
  75597. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  75598. worldDirection.normalize();
  75599. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  75600. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  75601. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  75602. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  75603. // Handle Integer types.
  75604. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75605. r /= 255;
  75606. g /= 255;
  75607. b /= 255;
  75608. }
  75609. // Handle Gamma space textures.
  75610. if (cubeInfo.gammaSpace) {
  75611. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  75612. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  75613. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  75614. }
  75615. var color = new BABYLON.Color3(r, g, b);
  75616. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  75617. totalSolidAngle += deltaSolidAngle;
  75618. u += du;
  75619. }
  75620. v += dv;
  75621. }
  75622. }
  75623. // Solid angle for entire sphere is 4*pi
  75624. var sphereSolidAngle = 4.0 * Math.PI;
  75625. // Adjust the solid angle to allow for how many faces we processed.
  75626. var facesProcessed = 6.0;
  75627. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  75628. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  75629. // This is needed because the numerical integration over the cube uses a
  75630. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  75631. // and also to compensate for accumulative error due to float precision in the summation.
  75632. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  75633. sphericalHarmonics.scale(correctionFactor);
  75634. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  75635. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  75636. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  75637. };
  75638. CubeMapToSphericalPolynomialTools.FileFaces = [
  75639. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  75640. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  75641. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  75642. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  75643. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  75644. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  75645. ];
  75646. return CubeMapToSphericalPolynomialTools;
  75647. }());
  75648. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  75649. })(BABYLON || (BABYLON = {}));
  75650. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  75651. "use strict";
  75652. var BABYLON;
  75653. (function (BABYLON) {
  75654. /**
  75655. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  75656. */
  75657. var PanoramaToCubeMapTools = /** @class */ (function () {
  75658. function PanoramaToCubeMapTools() {
  75659. }
  75660. /**
  75661. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  75662. *
  75663. * @param float32Array The source data.
  75664. * @param inputWidth The width of the input panorama.
  75665. * @param inputhHeight The height of the input panorama.
  75666. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  75667. * @return The cubemap data
  75668. */
  75669. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  75670. if (!float32Array) {
  75671. throw "ConvertPanoramaToCubemap: input cannot be null";
  75672. }
  75673. if (float32Array.length != inputWidth * inputHeight * 3) {
  75674. throw "ConvertPanoramaToCubemap: input size is wrong";
  75675. }
  75676. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  75677. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  75678. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  75679. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  75680. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  75681. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  75682. return {
  75683. front: textureFront,
  75684. back: textureBack,
  75685. left: textureLeft,
  75686. right: textureRight,
  75687. up: textureUp,
  75688. down: textureDown,
  75689. size: size,
  75690. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  75691. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  75692. gammaSpace: false,
  75693. };
  75694. };
  75695. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  75696. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  75697. var textureArray = new Float32Array(buffer);
  75698. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  75699. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  75700. var dy = 1 / texSize;
  75701. var fy = 0;
  75702. for (var y = 0; y < texSize; y++) {
  75703. var xv1 = faceData[0];
  75704. var xv2 = faceData[2];
  75705. for (var x = 0; x < texSize; x++) {
  75706. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  75707. v.normalize();
  75708. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  75709. // 3 channels per pixels
  75710. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  75711. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  75712. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  75713. xv1 = xv1.add(rotDX1);
  75714. xv2 = xv2.add(rotDX2);
  75715. }
  75716. fy += dy;
  75717. }
  75718. return textureArray;
  75719. };
  75720. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  75721. var theta = Math.atan2(vDir.z, vDir.x);
  75722. var phi = Math.acos(vDir.y);
  75723. while (theta < -Math.PI)
  75724. theta += 2 * Math.PI;
  75725. while (theta > Math.PI)
  75726. theta -= 2 * Math.PI;
  75727. var dx = theta / Math.PI;
  75728. var dy = phi / Math.PI;
  75729. // recenter.
  75730. dx = dx * 0.5 + 0.5;
  75731. var px = Math.round(dx * inputWidth);
  75732. if (px < 0)
  75733. px = 0;
  75734. else if (px >= inputWidth)
  75735. px = inputWidth - 1;
  75736. var py = Math.round(dy * inputHeight);
  75737. if (py < 0)
  75738. py = 0;
  75739. else if (py >= inputHeight)
  75740. py = inputHeight - 1;
  75741. var inputY = (inputHeight - py - 1);
  75742. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  75743. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  75744. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  75745. return {
  75746. r: r,
  75747. g: g,
  75748. b: b
  75749. };
  75750. };
  75751. PanoramaToCubeMapTools.FACE_FRONT = [
  75752. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75753. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75754. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75755. new BABYLON.Vector3(1.0, 1.0, -1.0)
  75756. ];
  75757. PanoramaToCubeMapTools.FACE_BACK = [
  75758. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75759. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75760. new BABYLON.Vector3(1.0, 1.0, 1.0),
  75761. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  75762. ];
  75763. PanoramaToCubeMapTools.FACE_RIGHT = [
  75764. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75765. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75766. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75767. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75768. ];
  75769. PanoramaToCubeMapTools.FACE_LEFT = [
  75770. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75771. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75772. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75773. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  75774. ];
  75775. PanoramaToCubeMapTools.FACE_DOWN = [
  75776. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75777. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75778. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75779. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75780. ];
  75781. PanoramaToCubeMapTools.FACE_UP = [
  75782. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75783. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75784. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75785. new BABYLON.Vector3(1.0, -1.0, -1.0)
  75786. ];
  75787. return PanoramaToCubeMapTools;
  75788. }());
  75789. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  75790. })(BABYLON || (BABYLON = {}));
  75791. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  75792. "use strict";
  75793. var BABYLON;
  75794. (function (BABYLON) {
  75795. ;
  75796. /**
  75797. * This groups tools to convert HDR texture to native colors array.
  75798. */
  75799. var HDRTools = /** @class */ (function () {
  75800. function HDRTools() {
  75801. }
  75802. HDRTools.Ldexp = function (mantissa, exponent) {
  75803. if (exponent > 1023) {
  75804. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  75805. }
  75806. if (exponent < -1074) {
  75807. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  75808. }
  75809. return mantissa * Math.pow(2, exponent);
  75810. };
  75811. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  75812. if (exponent > 0) {
  75813. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  75814. float32array[index + 0] = red * exponent;
  75815. float32array[index + 1] = green * exponent;
  75816. float32array[index + 2] = blue * exponent;
  75817. }
  75818. else {
  75819. float32array[index + 0] = 0;
  75820. float32array[index + 1] = 0;
  75821. float32array[index + 2] = 0;
  75822. }
  75823. };
  75824. HDRTools.readStringLine = function (uint8array, startIndex) {
  75825. var line = "";
  75826. var character = "";
  75827. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  75828. character = String.fromCharCode(uint8array[i]);
  75829. if (character == "\n") {
  75830. break;
  75831. }
  75832. line += character;
  75833. }
  75834. return line;
  75835. };
  75836. /**
  75837. * Reads header information from an RGBE texture stored in a native array.
  75838. * More information on this format are available here:
  75839. * https://en.wikipedia.org/wiki/RGBE_image_format
  75840. *
  75841. * @param uint8array The binary file stored in native array.
  75842. * @return The header information.
  75843. */
  75844. HDRTools.RGBE_ReadHeader = function (uint8array) {
  75845. var height = 0;
  75846. var width = 0;
  75847. var line = this.readStringLine(uint8array, 0);
  75848. if (line[0] != '#' || line[1] != '?') {
  75849. throw "Bad HDR Format.";
  75850. }
  75851. var endOfHeader = false;
  75852. var findFormat = false;
  75853. var lineIndex = 0;
  75854. do {
  75855. lineIndex += (line.length + 1);
  75856. line = this.readStringLine(uint8array, lineIndex);
  75857. if (line == "FORMAT=32-bit_rle_rgbe") {
  75858. findFormat = true;
  75859. }
  75860. else if (line.length == 0) {
  75861. endOfHeader = true;
  75862. }
  75863. } while (!endOfHeader);
  75864. if (!findFormat) {
  75865. throw "HDR Bad header format, unsupported FORMAT";
  75866. }
  75867. lineIndex += (line.length + 1);
  75868. line = this.readStringLine(uint8array, lineIndex);
  75869. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  75870. var match = sizeRegexp.exec(line);
  75871. // TODO. Support +Y and -X if needed.
  75872. if (!match || match.length < 3) {
  75873. throw "HDR Bad header format, no size";
  75874. }
  75875. width = parseInt(match[2]);
  75876. height = parseInt(match[1]);
  75877. if (width < 8 || width > 0x7fff) {
  75878. throw "HDR Bad header format, unsupported size";
  75879. }
  75880. lineIndex += (line.length + 1);
  75881. return {
  75882. height: height,
  75883. width: width,
  75884. dataPosition: lineIndex
  75885. };
  75886. };
  75887. /**
  75888. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75889. * This RGBE texture needs to store the information as a panorama.
  75890. *
  75891. * More information on this format are available here:
  75892. * https://en.wikipedia.org/wiki/RGBE_image_format
  75893. *
  75894. * @param buffer The binary file stored in an array buffer.
  75895. * @param size The expected size of the extracted cubemap.
  75896. * @return The Cube Map information.
  75897. */
  75898. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75899. var uint8array = new Uint8Array(buffer);
  75900. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75901. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75902. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75903. return cubeMapData;
  75904. };
  75905. /**
  75906. * Returns the pixels data extracted from an RGBE texture.
  75907. * This pixels will be stored left to right up to down in the R G B order in one array.
  75908. *
  75909. * More information on this format are available here:
  75910. * https://en.wikipedia.org/wiki/RGBE_image_format
  75911. *
  75912. * @param uint8array The binary file stored in an array buffer.
  75913. * @param hdrInfo The header information of the file.
  75914. * @return The pixels data in RGB right to left up to down order.
  75915. */
  75916. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75917. // Keep for multi format supports.
  75918. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75919. };
  75920. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75921. var num_scanlines = hdrInfo.height;
  75922. var scanline_width = hdrInfo.width;
  75923. var a, b, c, d, count;
  75924. var dataIndex = hdrInfo.dataPosition;
  75925. var index = 0, endIndex = 0, i = 0;
  75926. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75927. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75928. // 3 channels of 4 bytes per pixel in float.
  75929. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75930. var resultArray = new Float32Array(resultBuffer);
  75931. // read in each successive scanline
  75932. while (num_scanlines > 0) {
  75933. a = uint8array[dataIndex++];
  75934. b = uint8array[dataIndex++];
  75935. c = uint8array[dataIndex++];
  75936. d = uint8array[dataIndex++];
  75937. if (a != 2 || b != 2 || (c & 0x80)) {
  75938. // this file is not run length encoded
  75939. throw "HDR Bad header format, not RLE";
  75940. }
  75941. if (((c << 8) | d) != scanline_width) {
  75942. throw "HDR Bad header format, wrong scan line width";
  75943. }
  75944. index = 0;
  75945. // read each of the four channels for the scanline into the buffer
  75946. for (i = 0; i < 4; i++) {
  75947. endIndex = (i + 1) * scanline_width;
  75948. while (index < endIndex) {
  75949. a = uint8array[dataIndex++];
  75950. b = uint8array[dataIndex++];
  75951. if (a > 128) {
  75952. // a run of the same value
  75953. count = a - 128;
  75954. if ((count == 0) || (count > endIndex - index)) {
  75955. throw "HDR Bad Format, bad scanline data (run)";
  75956. }
  75957. while (count-- > 0) {
  75958. scanLineArray[index++] = b;
  75959. }
  75960. }
  75961. else {
  75962. // a non-run
  75963. count = a;
  75964. if ((count == 0) || (count > endIndex - index)) {
  75965. throw "HDR Bad Format, bad scanline data (non-run)";
  75966. }
  75967. scanLineArray[index++] = b;
  75968. if (--count > 0) {
  75969. for (var j = 0; j < count; j++) {
  75970. scanLineArray[index++] = uint8array[dataIndex++];
  75971. }
  75972. }
  75973. }
  75974. }
  75975. }
  75976. // now convert data from buffer into floats
  75977. for (i = 0; i < scanline_width; i++) {
  75978. a = scanLineArray[i];
  75979. b = scanLineArray[i + scanline_width];
  75980. c = scanLineArray[i + 2 * scanline_width];
  75981. d = scanLineArray[i + 3 * scanline_width];
  75982. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75983. }
  75984. num_scanlines--;
  75985. }
  75986. return resultArray;
  75987. };
  75988. return HDRTools;
  75989. }());
  75990. BABYLON.HDRTools = HDRTools;
  75991. })(BABYLON || (BABYLON = {}));
  75992. //# sourceMappingURL=babylon.hdr.js.map
  75993. "use strict";
  75994. var BABYLON;
  75995. (function (BABYLON) {
  75996. /**
  75997. * This represents a texture coming from an HDR input.
  75998. *
  75999. * The only supported format is currently panorama picture stored in RGBE format.
  76000. * Example of such files can be found on HDRLib: http://hdrlib.com/
  76001. */
  76002. var HDRCubeTexture = /** @class */ (function (_super) {
  76003. __extends(HDRCubeTexture, _super);
  76004. /**
  76005. * Instantiates an HDRTexture from the following parameters.
  76006. *
  76007. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  76008. * @param scene The scene the texture will be used in
  76009. * @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.
  76010. * @param noMipmap Forces to not generate the mipmap if true
  76011. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  76012. * @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)
  76013. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  76014. */
  76015. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  76016. if (noMipmap === void 0) { noMipmap = false; }
  76017. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76018. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76019. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76020. if (onLoad === void 0) { onLoad = null; }
  76021. if (onError === void 0) { onError = null; }
  76022. var _this = _super.call(this, scene) || this;
  76023. _this._useInGammaSpace = false;
  76024. _this._generateHarmonics = true;
  76025. _this._isBABYLONPreprocessed = false;
  76026. _this._onLoad = null;
  76027. _this._onError = null;
  76028. /**
  76029. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  76030. */
  76031. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  76032. /**
  76033. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  76034. * This is usefull at run time to apply the good shader.
  76035. */
  76036. _this.isPMREM = false;
  76037. _this._isBlocking = true;
  76038. /**
  76039. * Gets or sets the center of the bounding box associated with the cube texture
  76040. * It must define where the camera used to render the texture was set
  76041. */
  76042. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  76043. if (!url) {
  76044. return _this;
  76045. }
  76046. _this.name = url;
  76047. _this.url = url;
  76048. _this.hasAlpha = false;
  76049. _this.isCube = true;
  76050. _this._textureMatrix = BABYLON.Matrix.Identity();
  76051. _this._onLoad = onLoad;
  76052. _this._onError = onError;
  76053. _this.gammaSpace = false;
  76054. var caps = scene.getEngine().getCaps();
  76055. if (size) {
  76056. _this._isBABYLONPreprocessed = false;
  76057. _this._noMipmap = noMipmap;
  76058. _this._size = size;
  76059. _this._useInGammaSpace = useInGammaSpace;
  76060. _this._usePMREMGenerator = usePMREMGenerator &&
  76061. caps.textureLOD &&
  76062. caps.textureFloat &&
  76063. !_this._useInGammaSpace;
  76064. }
  76065. else {
  76066. _this._isBABYLONPreprocessed = true;
  76067. _this._noMipmap = false;
  76068. _this._useInGammaSpace = false;
  76069. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  76070. !_this._useInGammaSpace;
  76071. }
  76072. _this.isPMREM = _this._usePMREMGenerator;
  76073. _this._texture = _this._getFromCache(url, _this._noMipmap);
  76074. if (!_this._texture) {
  76075. if (!scene.useDelayedTextureLoading) {
  76076. _this.loadTexture();
  76077. }
  76078. else {
  76079. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  76080. }
  76081. }
  76082. return _this;
  76083. }
  76084. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  76085. /**
  76086. * Gets wether or not the texture is blocking during loading.
  76087. */
  76088. get: function () {
  76089. return this._isBlocking;
  76090. },
  76091. /**
  76092. * Sets wether or not the texture is blocking during loading.
  76093. */
  76094. set: function (value) {
  76095. this._isBlocking = value;
  76096. },
  76097. enumerable: true,
  76098. configurable: true
  76099. });
  76100. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  76101. get: function () {
  76102. return this._boundingBoxSize;
  76103. },
  76104. /**
  76105. * Gets or sets the size of the bounding box associated with the cube texture
  76106. * When defined, the cubemap will switch to local mode
  76107. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  76108. * @example https://www.babylonjs-playground.com/#RNASML
  76109. */
  76110. set: function (value) {
  76111. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  76112. return;
  76113. }
  76114. this._boundingBoxSize = value;
  76115. var scene = this.getScene();
  76116. if (scene) {
  76117. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  76118. }
  76119. },
  76120. enumerable: true,
  76121. configurable: true
  76122. });
  76123. /**
  76124. * Occurs when the file is a preprocessed .babylon.hdr file.
  76125. */
  76126. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  76127. var _this = this;
  76128. var mipLevels = 0;
  76129. var floatArrayView = null;
  76130. var scene = this.getScene();
  76131. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  76132. var mips = new Array();
  76133. if (!floatArrayView) {
  76134. return mips;
  76135. }
  76136. var startIndex = 30;
  76137. for (var level = 0; level < mipLevels; level++) {
  76138. mips.push([]);
  76139. // Fill each pixel of the mip level.
  76140. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  76141. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  76142. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  76143. mips[level].push(faceData);
  76144. startIndex += faceSize;
  76145. }
  76146. }
  76147. return mips;
  76148. } : null;
  76149. var callback = function (buffer) {
  76150. var scene = _this.getScene();
  76151. if (!scene) {
  76152. return null;
  76153. }
  76154. // Create Native Array Views
  76155. var intArrayView = new Int32Array(buffer);
  76156. floatArrayView = new Float32Array(buffer);
  76157. // Fill header.
  76158. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  76159. _this._size = intArrayView[1]; // CubeMap max mip face size.
  76160. // Update Texture Information.
  76161. if (!_this._texture) {
  76162. return null;
  76163. }
  76164. _this._texture.updateSize(_this._size, _this._size);
  76165. // Fill polynomial information.
  76166. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  76167. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  76168. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  76169. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  76170. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  76171. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  76172. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  76173. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  76174. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  76175. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  76176. _this.sphericalPolynomial = sphericalPolynomial;
  76177. // Fill pixel data.
  76178. mipLevels = intArrayView[29]; // Number of mip levels.
  76179. var startIndex = 30;
  76180. var data = [];
  76181. var faceSize = Math.pow(_this._size, 2) * 3;
  76182. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  76183. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  76184. startIndex += faceSize;
  76185. }
  76186. var results = [];
  76187. var byteArray = null;
  76188. // Push each faces.
  76189. for (var k = 0; k < 6; k++) {
  76190. var dataFace = null;
  76191. // To be deprecated.
  76192. if (version === 1) {
  76193. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  76194. dataFace = data[j];
  76195. }
  76196. // If special cases.
  76197. if (!mipmapGenerator && dataFace) {
  76198. if (!scene.getEngine().getCaps().textureFloat) {
  76199. // 3 channels of 1 bytes per pixel in bytes.
  76200. var byteBuffer = new ArrayBuffer(faceSize);
  76201. byteArray = new Uint8Array(byteBuffer);
  76202. }
  76203. for (var i = 0; i < _this._size * _this._size; i++) {
  76204. // Put in gamma space if requested.
  76205. if (_this._useInGammaSpace) {
  76206. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  76207. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  76208. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  76209. }
  76210. // Convert to int texture for fallback.
  76211. if (byteArray) {
  76212. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  76213. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  76214. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  76215. // May use luminance instead if the result is not accurate.
  76216. var max = Math.max(Math.max(r, g), b);
  76217. if (max > 255) {
  76218. var scale = 255 / max;
  76219. r *= scale;
  76220. g *= scale;
  76221. b *= scale;
  76222. }
  76223. byteArray[(i * 3) + 0] = r;
  76224. byteArray[(i * 3) + 1] = g;
  76225. byteArray[(i * 3) + 2] = b;
  76226. }
  76227. }
  76228. }
  76229. // Fill the array accordingly.
  76230. if (byteArray) {
  76231. results.push(byteArray);
  76232. }
  76233. else {
  76234. results.push(dataFace);
  76235. }
  76236. }
  76237. return results;
  76238. };
  76239. if (scene) {
  76240. 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);
  76241. }
  76242. };
  76243. /**
  76244. * Occurs when the file is raw .hdr file.
  76245. */
  76246. HDRCubeTexture.prototype.loadHDRTexture = function () {
  76247. var _this = this;
  76248. var callback = function (buffer) {
  76249. var scene = _this.getScene();
  76250. if (!scene) {
  76251. return null;
  76252. }
  76253. // Extract the raw linear data.
  76254. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  76255. // Generate harmonics if needed.
  76256. if (_this._generateHarmonics) {
  76257. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  76258. _this.sphericalPolynomial = sphericalPolynomial;
  76259. }
  76260. var results = [];
  76261. var byteArray = null;
  76262. // Push each faces.
  76263. for (var j = 0; j < 6; j++) {
  76264. // Create uintarray fallback.
  76265. if (!scene.getEngine().getCaps().textureFloat) {
  76266. // 3 channels of 1 bytes per pixel in bytes.
  76267. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  76268. byteArray = new Uint8Array(byteBuffer);
  76269. }
  76270. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  76271. // If special cases.
  76272. if (_this._useInGammaSpace || byteArray) {
  76273. for (var i = 0; i < _this._size * _this._size; i++) {
  76274. // Put in gamma space if requested.
  76275. if (_this._useInGammaSpace) {
  76276. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  76277. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  76278. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  76279. }
  76280. // Convert to int texture for fallback.
  76281. if (byteArray) {
  76282. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  76283. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  76284. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  76285. // May use luminance instead if the result is not accurate.
  76286. var max = Math.max(Math.max(r, g), b);
  76287. if (max > 255) {
  76288. var scale = 255 / max;
  76289. r *= scale;
  76290. g *= scale;
  76291. b *= scale;
  76292. }
  76293. byteArray[(i * 3) + 0] = r;
  76294. byteArray[(i * 3) + 1] = g;
  76295. byteArray[(i * 3) + 2] = b;
  76296. }
  76297. }
  76298. }
  76299. if (byteArray) {
  76300. results.push(byteArray);
  76301. }
  76302. else {
  76303. results.push(dataFace);
  76304. }
  76305. }
  76306. return results;
  76307. };
  76308. var mipmapGenerator = null;
  76309. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  76310. // if (!this._noMipmap &&
  76311. // this._usePMREMGenerator) {
  76312. // mipmapGenerator = (data: ArrayBufferView[]) => {
  76313. // // Custom setup of the generator matching with the PBR shader values.
  76314. // var generator = new BABYLON.PMREMGenerator(data,
  76315. // this._size,
  76316. // this._size,
  76317. // 0,
  76318. // 3,
  76319. // this.getScene().getEngine().getCaps().textureFloat,
  76320. // 2048,
  76321. // 0.25,
  76322. // false,
  76323. // true);
  76324. // return generator.filterCubeMap();
  76325. // };
  76326. // }
  76327. var scene = this.getScene();
  76328. if (scene) {
  76329. 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);
  76330. }
  76331. };
  76332. /**
  76333. * Starts the loading process of the texture.
  76334. */
  76335. HDRCubeTexture.prototype.loadTexture = function () {
  76336. if (this._isBABYLONPreprocessed) {
  76337. this.loadBabylonTexture();
  76338. }
  76339. else {
  76340. this.loadHDRTexture();
  76341. }
  76342. };
  76343. HDRCubeTexture.prototype.clone = function () {
  76344. var scene = this.getScene();
  76345. if (!scene) {
  76346. return this;
  76347. }
  76348. var size = (this._isBABYLONPreprocessed ? null : this._size);
  76349. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  76350. // Base texture
  76351. newTexture.level = this.level;
  76352. newTexture.wrapU = this.wrapU;
  76353. newTexture.wrapV = this.wrapV;
  76354. newTexture.coordinatesIndex = this.coordinatesIndex;
  76355. newTexture.coordinatesMode = this.coordinatesMode;
  76356. return newTexture;
  76357. };
  76358. // Methods
  76359. HDRCubeTexture.prototype.delayLoad = function () {
  76360. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  76361. return;
  76362. }
  76363. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  76364. this._texture = this._getFromCache(this.url, this._noMipmap);
  76365. if (!this._texture) {
  76366. this.loadTexture();
  76367. }
  76368. };
  76369. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  76370. return this._textureMatrix;
  76371. };
  76372. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  76373. this._textureMatrix = value;
  76374. };
  76375. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  76376. var texture = null;
  76377. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  76378. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  76379. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  76380. texture.name = parsedTexture.name;
  76381. texture.hasAlpha = parsedTexture.hasAlpha;
  76382. texture.level = parsedTexture.level;
  76383. texture.coordinatesMode = parsedTexture.coordinatesMode;
  76384. texture.isBlocking = parsedTexture.isBlocking;
  76385. }
  76386. if (texture) {
  76387. if (parsedTexture.boundingBoxPosition) {
  76388. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  76389. }
  76390. if (parsedTexture.boundingBoxSize) {
  76391. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  76392. }
  76393. }
  76394. return texture;
  76395. };
  76396. HDRCubeTexture.prototype.serialize = function () {
  76397. if (!this.name) {
  76398. return null;
  76399. }
  76400. var serializationObject = {};
  76401. serializationObject.name = this.name;
  76402. serializationObject.hasAlpha = this.hasAlpha;
  76403. serializationObject.isCube = true;
  76404. serializationObject.level = this.level;
  76405. serializationObject.size = this._size;
  76406. serializationObject.coordinatesMode = this.coordinatesMode;
  76407. serializationObject.useInGammaSpace = this._useInGammaSpace;
  76408. serializationObject.generateHarmonics = this._generateHarmonics;
  76409. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  76410. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  76411. serializationObject.customType = "BABYLON.HDRCubeTexture";
  76412. serializationObject.noMipmap = this._noMipmap;
  76413. serializationObject.isBlocking = this._isBlocking;
  76414. return serializationObject;
  76415. };
  76416. /**
  76417. * Saves as a file the data contained in the texture in a binary format.
  76418. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  76419. * as the spherical used in the lighting.
  76420. * @param url The HDR file url.
  76421. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  76422. * @param onError Method called if any error happens during download.
  76423. * @return The packed binary data.
  76424. */
  76425. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  76426. if (onError === void 0) { onError = null; }
  76427. var callback = function (buffer) {
  76428. var data = new Blob([buffer], { type: 'application/octet-stream' });
  76429. // Returns a URL you can use as a href.
  76430. var objUrl = window.URL.createObjectURL(data);
  76431. // Simulates a link to it and click to dowload.
  76432. var a = document.createElement("a");
  76433. document.body.appendChild(a);
  76434. a.style.display = "none";
  76435. a.href = objUrl;
  76436. a.download = "envmap.babylon.hdr";
  76437. a.click();
  76438. };
  76439. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  76440. };
  76441. /**
  76442. * Serializes the data contained in the texture in a binary format.
  76443. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  76444. * as the spherical used in the lighting.
  76445. * @param url The HDR file url.
  76446. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  76447. * @param onError Method called if any error happens during download.
  76448. * @return The packed binary data.
  76449. */
  76450. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  76451. if (onError === void 0) { onError = null; }
  76452. // Needs the url tho create the texture.
  76453. if (!url) {
  76454. return;
  76455. }
  76456. // Check Power of two size.
  76457. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  76458. return;
  76459. }
  76460. // Coming Back in 3.x.
  76461. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  76462. };
  76463. HDRCubeTexture._facesMapping = [
  76464. "right",
  76465. "left",
  76466. "up",
  76467. "down",
  76468. "front",
  76469. "back"
  76470. ];
  76471. return HDRCubeTexture;
  76472. }(BABYLON.BaseTexture));
  76473. BABYLON.HDRCubeTexture = HDRCubeTexture;
  76474. })(BABYLON || (BABYLON = {}));
  76475. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  76476. "use strict";
  76477. var BABYLON;
  76478. (function (BABYLON) {
  76479. var IndexedVector2 = /** @class */ (function (_super) {
  76480. __extends(IndexedVector2, _super);
  76481. function IndexedVector2(original, index) {
  76482. var _this = _super.call(this, original.x, original.y) || this;
  76483. _this.index = index;
  76484. return _this;
  76485. }
  76486. return IndexedVector2;
  76487. }(BABYLON.Vector2));
  76488. var PolygonPoints = /** @class */ (function () {
  76489. function PolygonPoints() {
  76490. this.elements = new Array();
  76491. }
  76492. PolygonPoints.prototype.add = function (originalPoints) {
  76493. var _this = this;
  76494. var result = new Array();
  76495. originalPoints.forEach(function (point) {
  76496. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76497. var newPoint = new IndexedVector2(point, _this.elements.length);
  76498. result.push(newPoint);
  76499. _this.elements.push(newPoint);
  76500. }
  76501. });
  76502. return result;
  76503. };
  76504. PolygonPoints.prototype.computeBounds = function () {
  76505. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76506. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76507. this.elements.forEach(function (point) {
  76508. // x
  76509. if (point.x < lmin.x) {
  76510. lmin.x = point.x;
  76511. }
  76512. else if (point.x > lmax.x) {
  76513. lmax.x = point.x;
  76514. }
  76515. // y
  76516. if (point.y < lmin.y) {
  76517. lmin.y = point.y;
  76518. }
  76519. else if (point.y > lmax.y) {
  76520. lmax.y = point.y;
  76521. }
  76522. });
  76523. return {
  76524. min: lmin,
  76525. max: lmax,
  76526. width: lmax.x - lmin.x,
  76527. height: lmax.y - lmin.y
  76528. };
  76529. };
  76530. return PolygonPoints;
  76531. }());
  76532. var Polygon = /** @class */ (function () {
  76533. function Polygon() {
  76534. }
  76535. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76536. return [
  76537. new BABYLON.Vector2(xmin, ymin),
  76538. new BABYLON.Vector2(xmax, ymin),
  76539. new BABYLON.Vector2(xmax, ymax),
  76540. new BABYLON.Vector2(xmin, ymax)
  76541. ];
  76542. };
  76543. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76544. if (cx === void 0) { cx = 0; }
  76545. if (cy === void 0) { cy = 0; }
  76546. if (numberOfSides === void 0) { numberOfSides = 32; }
  76547. var result = new Array();
  76548. var angle = 0;
  76549. var increment = (Math.PI * 2) / numberOfSides;
  76550. for (var i = 0; i < numberOfSides; i++) {
  76551. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76552. angle -= increment;
  76553. }
  76554. return result;
  76555. };
  76556. Polygon.Parse = function (input) {
  76557. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76558. var i, result = [];
  76559. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76560. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76561. }
  76562. return result;
  76563. };
  76564. Polygon.StartingAt = function (x, y) {
  76565. return BABYLON.Path2.StartingAt(x, y);
  76566. };
  76567. return Polygon;
  76568. }());
  76569. BABYLON.Polygon = Polygon;
  76570. var PolygonMeshBuilder = /** @class */ (function () {
  76571. function PolygonMeshBuilder(name, contours, scene) {
  76572. this._points = new PolygonPoints();
  76573. this._outlinepoints = new PolygonPoints();
  76574. this._holes = new Array();
  76575. this._epoints = new Array();
  76576. this._eholes = new Array();
  76577. this._name = name;
  76578. this._scene = scene;
  76579. var points;
  76580. if (contours instanceof BABYLON.Path2) {
  76581. points = contours.getPoints();
  76582. }
  76583. else {
  76584. points = contours;
  76585. }
  76586. this._addToepoint(points);
  76587. this._points.add(points);
  76588. this._outlinepoints.add(points);
  76589. if (typeof earcut === 'undefined') {
  76590. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  76591. }
  76592. }
  76593. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76594. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76595. var p = points_1[_i];
  76596. this._epoints.push(p.x, p.y);
  76597. }
  76598. };
  76599. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76600. this._points.add(hole);
  76601. var holepoints = new PolygonPoints();
  76602. holepoints.add(hole);
  76603. this._holes.push(holepoints);
  76604. this._eholes.push(this._epoints.length / 2);
  76605. this._addToepoint(hole);
  76606. return this;
  76607. };
  76608. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76609. var _this = this;
  76610. if (updatable === void 0) { updatable = false; }
  76611. if (depth === void 0) { depth = 0; }
  76612. var result = new BABYLON.Mesh(this._name, this._scene);
  76613. var normals = new Array();
  76614. var positions = new Array();
  76615. var uvs = new Array();
  76616. var bounds = this._points.computeBounds();
  76617. this._points.elements.forEach(function (p) {
  76618. normals.push(0, 1.0, 0);
  76619. positions.push(p.x, 0, p.y);
  76620. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76621. });
  76622. var indices = new Array();
  76623. var res = earcut(this._epoints, this._eholes, 2);
  76624. for (var i = 0; i < res.length; i++) {
  76625. indices.push(res[i]);
  76626. }
  76627. if (depth > 0) {
  76628. var positionscount = (positions.length / 3); //get the current pointcount
  76629. this._points.elements.forEach(function (p) {
  76630. normals.push(0, -1.0, 0);
  76631. positions.push(p.x, -depth, p.y);
  76632. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76633. });
  76634. var totalCount = indices.length;
  76635. for (var i = 0; i < totalCount; i += 3) {
  76636. var i0 = indices[i + 0];
  76637. var i1 = indices[i + 1];
  76638. var i2 = indices[i + 2];
  76639. indices.push(i2 + positionscount);
  76640. indices.push(i1 + positionscount);
  76641. indices.push(i0 + positionscount);
  76642. }
  76643. //Add the sides
  76644. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76645. this._holes.forEach(function (hole) {
  76646. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76647. });
  76648. }
  76649. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76650. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76651. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76652. result.setIndices(indices);
  76653. return result;
  76654. };
  76655. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76656. var StartIndex = positions.length / 3;
  76657. var ulength = 0;
  76658. for (var i = 0; i < points.elements.length; i++) {
  76659. var p = points.elements[i];
  76660. var p1;
  76661. if ((i + 1) > points.elements.length - 1) {
  76662. p1 = points.elements[0];
  76663. }
  76664. else {
  76665. p1 = points.elements[i + 1];
  76666. }
  76667. positions.push(p.x, 0, p.y);
  76668. positions.push(p.x, -depth, p.y);
  76669. positions.push(p1.x, 0, p1.y);
  76670. positions.push(p1.x, -depth, p1.y);
  76671. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76672. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76673. var v3 = v2.subtract(v1);
  76674. var v4 = new BABYLON.Vector3(0, 1, 0);
  76675. var vn = BABYLON.Vector3.Cross(v3, v4);
  76676. vn = vn.normalize();
  76677. uvs.push(ulength / bounds.width, 0);
  76678. uvs.push(ulength / bounds.width, 1);
  76679. ulength += v3.length();
  76680. uvs.push((ulength / bounds.width), 0);
  76681. uvs.push((ulength / bounds.width), 1);
  76682. if (!flip) {
  76683. normals.push(-vn.x, -vn.y, -vn.z);
  76684. normals.push(-vn.x, -vn.y, -vn.z);
  76685. normals.push(-vn.x, -vn.y, -vn.z);
  76686. normals.push(-vn.x, -vn.y, -vn.z);
  76687. indices.push(StartIndex);
  76688. indices.push(StartIndex + 1);
  76689. indices.push(StartIndex + 2);
  76690. indices.push(StartIndex + 1);
  76691. indices.push(StartIndex + 3);
  76692. indices.push(StartIndex + 2);
  76693. }
  76694. else {
  76695. normals.push(vn.x, vn.y, vn.z);
  76696. normals.push(vn.x, vn.y, vn.z);
  76697. normals.push(vn.x, vn.y, vn.z);
  76698. normals.push(vn.x, vn.y, vn.z);
  76699. indices.push(StartIndex);
  76700. indices.push(StartIndex + 2);
  76701. indices.push(StartIndex + 1);
  76702. indices.push(StartIndex + 1);
  76703. indices.push(StartIndex + 2);
  76704. indices.push(StartIndex + 3);
  76705. }
  76706. StartIndex += 4;
  76707. }
  76708. ;
  76709. };
  76710. return PolygonMeshBuilder;
  76711. }());
  76712. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76713. })(BABYLON || (BABYLON = {}));
  76714. //# sourceMappingURL=babylon.polygonMesh.js.map
  76715. "use strict";
  76716. var BABYLON;
  76717. (function (BABYLON) {
  76718. // Unique ID when we import meshes from Babylon to CSG
  76719. var currentCSGMeshId = 0;
  76720. // # class Vertex
  76721. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76722. // one to provide additional features like texture coordinates and vertex
  76723. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76724. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76725. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76726. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76727. // is not used anywhere else.
  76728. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76729. var Vertex = /** @class */ (function () {
  76730. function Vertex(pos, normal, uv) {
  76731. this.pos = pos;
  76732. this.normal = normal;
  76733. this.uv = uv;
  76734. }
  76735. Vertex.prototype.clone = function () {
  76736. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76737. };
  76738. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76739. // orientation of a polygon is flipped.
  76740. Vertex.prototype.flip = function () {
  76741. this.normal = this.normal.scale(-1);
  76742. };
  76743. // Create a new vertex between this vertex and `other` by linearly
  76744. // interpolating all properties using a parameter of `t`. Subclasses should
  76745. // override this to interpolate additional properties.
  76746. Vertex.prototype.interpolate = function (other, t) {
  76747. 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));
  76748. };
  76749. return Vertex;
  76750. }());
  76751. // # class Plane
  76752. // Represents a plane in 3D space.
  76753. var Plane = /** @class */ (function () {
  76754. function Plane(normal, w) {
  76755. this.normal = normal;
  76756. this.w = w;
  76757. }
  76758. Plane.FromPoints = function (a, b, c) {
  76759. var v0 = c.subtract(a);
  76760. var v1 = b.subtract(a);
  76761. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76762. return null;
  76763. }
  76764. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76765. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76766. };
  76767. Plane.prototype.clone = function () {
  76768. return new Plane(this.normal.clone(), this.w);
  76769. };
  76770. Plane.prototype.flip = function () {
  76771. this.normal.scaleInPlace(-1);
  76772. this.w = -this.w;
  76773. };
  76774. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76775. // fragments in the appropriate lists. Coplanar polygons go into either
  76776. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76777. // respect to this plane. Polygons in front or in back of this plane go into
  76778. // either `front` or `back`.
  76779. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76780. var COPLANAR = 0;
  76781. var FRONT = 1;
  76782. var BACK = 2;
  76783. var SPANNING = 3;
  76784. // Classify each point as well as the entire polygon into one of the above
  76785. // four classes.
  76786. var polygonType = 0;
  76787. var types = [];
  76788. var i;
  76789. var t;
  76790. for (i = 0; i < polygon.vertices.length; i++) {
  76791. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76792. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76793. polygonType |= type;
  76794. types.push(type);
  76795. }
  76796. // Put the polygon in the correct list, splitting it when necessary.
  76797. switch (polygonType) {
  76798. case COPLANAR:
  76799. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76800. break;
  76801. case FRONT:
  76802. front.push(polygon);
  76803. break;
  76804. case BACK:
  76805. back.push(polygon);
  76806. break;
  76807. case SPANNING:
  76808. var f = [], b = [];
  76809. for (i = 0; i < polygon.vertices.length; i++) {
  76810. var j = (i + 1) % polygon.vertices.length;
  76811. var ti = types[i], tj = types[j];
  76812. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76813. if (ti !== BACK)
  76814. f.push(vi);
  76815. if (ti !== FRONT)
  76816. b.push(ti !== BACK ? vi.clone() : vi);
  76817. if ((ti | tj) === SPANNING) {
  76818. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76819. var v = vi.interpolate(vj, t);
  76820. f.push(v);
  76821. b.push(v.clone());
  76822. }
  76823. }
  76824. var poly;
  76825. if (f.length >= 3) {
  76826. poly = new Polygon(f, polygon.shared);
  76827. if (poly.plane)
  76828. front.push(poly);
  76829. }
  76830. if (b.length >= 3) {
  76831. poly = new Polygon(b, polygon.shared);
  76832. if (poly.plane)
  76833. back.push(poly);
  76834. }
  76835. break;
  76836. }
  76837. };
  76838. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76839. // point is on the plane.
  76840. Plane.EPSILON = 1e-5;
  76841. return Plane;
  76842. }());
  76843. // # class Polygon
  76844. // Represents a convex polygon. The vertices used to initialize a polygon must
  76845. // be coplanar and form a convex loop.
  76846. //
  76847. // Each convex polygon has a `shared` property, which is shared between all
  76848. // polygons that are clones of each other or were split from the same polygon.
  76849. // This can be used to define per-polygon properties (such as surface color).
  76850. var Polygon = /** @class */ (function () {
  76851. function Polygon(vertices, shared) {
  76852. this.vertices = vertices;
  76853. this.shared = shared;
  76854. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76855. }
  76856. Polygon.prototype.clone = function () {
  76857. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76858. return new Polygon(vertices, this.shared);
  76859. };
  76860. Polygon.prototype.flip = function () {
  76861. this.vertices.reverse().map(function (v) { v.flip(); });
  76862. this.plane.flip();
  76863. };
  76864. return Polygon;
  76865. }());
  76866. // # class Node
  76867. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76868. // by picking a polygon to split along. That polygon (and all other coplanar
  76869. // polygons) are added directly to that node and the other polygons are added to
  76870. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76871. // no distinction between internal and leaf nodes.
  76872. var Node = /** @class */ (function () {
  76873. function Node(polygons) {
  76874. this.plane = null;
  76875. this.front = null;
  76876. this.back = null;
  76877. this.polygons = new Array();
  76878. if (polygons) {
  76879. this.build(polygons);
  76880. }
  76881. }
  76882. Node.prototype.clone = function () {
  76883. var node = new Node();
  76884. node.plane = this.plane && this.plane.clone();
  76885. node.front = this.front && this.front.clone();
  76886. node.back = this.back && this.back.clone();
  76887. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76888. return node;
  76889. };
  76890. // Convert solid space to empty space and empty space to solid space.
  76891. Node.prototype.invert = function () {
  76892. for (var i = 0; i < this.polygons.length; i++) {
  76893. this.polygons[i].flip();
  76894. }
  76895. if (this.plane) {
  76896. this.plane.flip();
  76897. }
  76898. if (this.front) {
  76899. this.front.invert();
  76900. }
  76901. if (this.back) {
  76902. this.back.invert();
  76903. }
  76904. var temp = this.front;
  76905. this.front = this.back;
  76906. this.back = temp;
  76907. };
  76908. // Recursively remove all polygons in `polygons` that are inside this BSP
  76909. // tree.
  76910. Node.prototype.clipPolygons = function (polygons) {
  76911. if (!this.plane)
  76912. return polygons.slice();
  76913. var front = new Array(), back = new Array();
  76914. for (var i = 0; i < polygons.length; i++) {
  76915. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76916. }
  76917. if (this.front) {
  76918. front = this.front.clipPolygons(front);
  76919. }
  76920. if (this.back) {
  76921. back = this.back.clipPolygons(back);
  76922. }
  76923. else {
  76924. back = [];
  76925. }
  76926. return front.concat(back);
  76927. };
  76928. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76929. // `bsp`.
  76930. Node.prototype.clipTo = function (bsp) {
  76931. this.polygons = bsp.clipPolygons(this.polygons);
  76932. if (this.front)
  76933. this.front.clipTo(bsp);
  76934. if (this.back)
  76935. this.back.clipTo(bsp);
  76936. };
  76937. // Return a list of all polygons in this BSP tree.
  76938. Node.prototype.allPolygons = function () {
  76939. var polygons = this.polygons.slice();
  76940. if (this.front)
  76941. polygons = polygons.concat(this.front.allPolygons());
  76942. if (this.back)
  76943. polygons = polygons.concat(this.back.allPolygons());
  76944. return polygons;
  76945. };
  76946. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76947. // new polygons are filtered down to the bottom of the tree and become new
  76948. // nodes there. Each set of polygons is partitioned using the first polygon
  76949. // (no heuristic is used to pick a good split).
  76950. Node.prototype.build = function (polygons) {
  76951. if (!polygons.length)
  76952. return;
  76953. if (!this.plane)
  76954. this.plane = polygons[0].plane.clone();
  76955. var front = new Array(), back = new Array();
  76956. for (var i = 0; i < polygons.length; i++) {
  76957. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76958. }
  76959. if (front.length) {
  76960. if (!this.front)
  76961. this.front = new Node();
  76962. this.front.build(front);
  76963. }
  76964. if (back.length) {
  76965. if (!this.back)
  76966. this.back = new Node();
  76967. this.back.build(back);
  76968. }
  76969. };
  76970. return Node;
  76971. }());
  76972. var CSG = /** @class */ (function () {
  76973. function CSG() {
  76974. this.polygons = new Array();
  76975. }
  76976. // Convert BABYLON.Mesh to BABYLON.CSG
  76977. CSG.FromMesh = function (mesh) {
  76978. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76979. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76980. if (mesh instanceof BABYLON.Mesh) {
  76981. mesh.computeWorldMatrix(true);
  76982. matrix = mesh.getWorldMatrix();
  76983. meshPosition = mesh.position.clone();
  76984. meshRotation = mesh.rotation.clone();
  76985. if (mesh.rotationQuaternion) {
  76986. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76987. }
  76988. meshScaling = mesh.scaling.clone();
  76989. }
  76990. else {
  76991. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76992. }
  76993. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76994. var subMeshes = mesh.subMeshes;
  76995. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76996. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76997. vertices = [];
  76998. for (var j = 0; j < 3; j++) {
  76999. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  77000. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  77001. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  77002. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  77003. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  77004. vertex = new Vertex(position, normal, uv);
  77005. vertices.push(vertex);
  77006. }
  77007. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  77008. // To handle the case of degenerated triangle
  77009. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  77010. if (polygon.plane)
  77011. polygons.push(polygon);
  77012. }
  77013. }
  77014. var csg = CSG.FromPolygons(polygons);
  77015. csg.matrix = matrix;
  77016. csg.position = meshPosition;
  77017. csg.rotation = meshRotation;
  77018. csg.scaling = meshScaling;
  77019. csg.rotationQuaternion = meshRotationQuaternion;
  77020. currentCSGMeshId++;
  77021. return csg;
  77022. };
  77023. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  77024. CSG.FromPolygons = function (polygons) {
  77025. var csg = new CSG();
  77026. csg.polygons = polygons;
  77027. return csg;
  77028. };
  77029. CSG.prototype.clone = function () {
  77030. var csg = new CSG();
  77031. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  77032. csg.copyTransformAttributes(this);
  77033. return csg;
  77034. };
  77035. CSG.prototype.union = function (csg) {
  77036. var a = new Node(this.clone().polygons);
  77037. var b = new Node(csg.clone().polygons);
  77038. a.clipTo(b);
  77039. b.clipTo(a);
  77040. b.invert();
  77041. b.clipTo(a);
  77042. b.invert();
  77043. a.build(b.allPolygons());
  77044. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  77045. };
  77046. CSG.prototype.unionInPlace = function (csg) {
  77047. var a = new Node(this.polygons);
  77048. var b = new Node(csg.polygons);
  77049. a.clipTo(b);
  77050. b.clipTo(a);
  77051. b.invert();
  77052. b.clipTo(a);
  77053. b.invert();
  77054. a.build(b.allPolygons());
  77055. this.polygons = a.allPolygons();
  77056. };
  77057. CSG.prototype.subtract = function (csg) {
  77058. var a = new Node(this.clone().polygons);
  77059. var b = new Node(csg.clone().polygons);
  77060. a.invert();
  77061. a.clipTo(b);
  77062. b.clipTo(a);
  77063. b.invert();
  77064. b.clipTo(a);
  77065. b.invert();
  77066. a.build(b.allPolygons());
  77067. a.invert();
  77068. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  77069. };
  77070. CSG.prototype.subtractInPlace = function (csg) {
  77071. var a = new Node(this.polygons);
  77072. var b = new Node(csg.polygons);
  77073. a.invert();
  77074. a.clipTo(b);
  77075. b.clipTo(a);
  77076. b.invert();
  77077. b.clipTo(a);
  77078. b.invert();
  77079. a.build(b.allPolygons());
  77080. a.invert();
  77081. this.polygons = a.allPolygons();
  77082. };
  77083. CSG.prototype.intersect = function (csg) {
  77084. var a = new Node(this.clone().polygons);
  77085. var b = new Node(csg.clone().polygons);
  77086. a.invert();
  77087. b.clipTo(a);
  77088. b.invert();
  77089. a.clipTo(b);
  77090. b.clipTo(a);
  77091. a.build(b.allPolygons());
  77092. a.invert();
  77093. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  77094. };
  77095. CSG.prototype.intersectInPlace = function (csg) {
  77096. var a = new Node(this.polygons);
  77097. var b = new Node(csg.polygons);
  77098. a.invert();
  77099. b.clipTo(a);
  77100. b.invert();
  77101. a.clipTo(b);
  77102. b.clipTo(a);
  77103. a.build(b.allPolygons());
  77104. a.invert();
  77105. this.polygons = a.allPolygons();
  77106. };
  77107. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  77108. // not modified.
  77109. CSG.prototype.inverse = function () {
  77110. var csg = this.clone();
  77111. csg.inverseInPlace();
  77112. return csg;
  77113. };
  77114. CSG.prototype.inverseInPlace = function () {
  77115. this.polygons.map(function (p) { p.flip(); });
  77116. };
  77117. // This is used to keep meshes transformations so they can be restored
  77118. // when we build back a Babylon Mesh
  77119. // NB : All CSG operations are performed in world coordinates
  77120. CSG.prototype.copyTransformAttributes = function (csg) {
  77121. this.matrix = csg.matrix;
  77122. this.position = csg.position;
  77123. this.rotation = csg.rotation;
  77124. this.scaling = csg.scaling;
  77125. this.rotationQuaternion = csg.rotationQuaternion;
  77126. return this;
  77127. };
  77128. // Build Raw mesh from CSG
  77129. // Coordinates here are in world space
  77130. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  77131. var matrix = this.matrix.clone();
  77132. matrix.invert();
  77133. 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;
  77134. if (keepSubMeshes) {
  77135. // Sort Polygons, since subMeshes are indices range
  77136. polygons.sort(function (a, b) {
  77137. if (a.shared.meshId === b.shared.meshId) {
  77138. return a.shared.subMeshId - b.shared.subMeshId;
  77139. }
  77140. else {
  77141. return a.shared.meshId - b.shared.meshId;
  77142. }
  77143. });
  77144. }
  77145. for (var i = 0, il = polygons.length; i < il; i++) {
  77146. polygon = polygons[i];
  77147. // Building SubMeshes
  77148. if (!subMesh_dict[polygon.shared.meshId]) {
  77149. subMesh_dict[polygon.shared.meshId] = {};
  77150. }
  77151. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  77152. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  77153. indexStart: +Infinity,
  77154. indexEnd: -Infinity,
  77155. materialIndex: polygon.shared.materialIndex
  77156. };
  77157. }
  77158. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  77159. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  77160. polygonIndices[0] = 0;
  77161. polygonIndices[1] = j - 1;
  77162. polygonIndices[2] = j;
  77163. for (var k = 0; k < 3; k++) {
  77164. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  77165. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  77166. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  77167. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  77168. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  77169. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  77170. // Check if 2 points can be merged
  77171. if (!(typeof vertex_idx !== 'undefined' &&
  77172. normals[vertex_idx * 3] === localNormal.x &&
  77173. normals[vertex_idx * 3 + 1] === localNormal.y &&
  77174. normals[vertex_idx * 3 + 2] === localNormal.z &&
  77175. uvs[vertex_idx * 2] === uv.x &&
  77176. uvs[vertex_idx * 2 + 1] === uv.y)) {
  77177. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  77178. uvs.push(uv.x, uv.y);
  77179. normals.push(normal.x, normal.y, normal.z);
  77180. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  77181. }
  77182. indices.push(vertex_idx);
  77183. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  77184. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  77185. currentIndex++;
  77186. }
  77187. }
  77188. }
  77189. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  77190. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  77191. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  77192. mesh.setIndices(indices, null);
  77193. if (keepSubMeshes) {
  77194. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  77195. var materialIndexOffset = 0, materialMaxIndex;
  77196. mesh.subMeshes = new Array();
  77197. for (var m in subMesh_dict) {
  77198. materialMaxIndex = -1;
  77199. for (var sm in subMesh_dict[m]) {
  77200. subMesh_obj = subMesh_dict[m][sm];
  77201. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  77202. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  77203. }
  77204. materialIndexOffset += ++materialMaxIndex;
  77205. }
  77206. }
  77207. return mesh;
  77208. };
  77209. // Build Mesh from CSG taking material and transforms into account
  77210. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  77211. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  77212. mesh.material = material;
  77213. mesh.position.copyFrom(this.position);
  77214. mesh.rotation.copyFrom(this.rotation);
  77215. if (this.rotationQuaternion) {
  77216. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  77217. }
  77218. mesh.scaling.copyFrom(this.scaling);
  77219. mesh.computeWorldMatrix(true);
  77220. return mesh;
  77221. };
  77222. return CSG;
  77223. }());
  77224. BABYLON.CSG = CSG;
  77225. })(BABYLON || (BABYLON = {}));
  77226. //# sourceMappingURL=babylon.csg.js.map
  77227. "use strict";
  77228. var BABYLON;
  77229. (function (BABYLON) {
  77230. var LensFlare = /** @class */ (function () {
  77231. function LensFlare(size, position, color, imgUrl, system) {
  77232. this.size = size;
  77233. this.position = position;
  77234. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77235. this.color = color || new BABYLON.Color3(1, 1, 1);
  77236. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  77237. this._system = system;
  77238. system.lensFlares.push(this);
  77239. }
  77240. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  77241. return new LensFlare(size, position, color, imgUrl, system);
  77242. };
  77243. LensFlare.prototype.dispose = function () {
  77244. if (this.texture) {
  77245. this.texture.dispose();
  77246. }
  77247. // Remove from scene
  77248. var index = this._system.lensFlares.indexOf(this);
  77249. this._system.lensFlares.splice(index, 1);
  77250. };
  77251. ;
  77252. return LensFlare;
  77253. }());
  77254. BABYLON.LensFlare = LensFlare;
  77255. })(BABYLON || (BABYLON = {}));
  77256. //# sourceMappingURL=babylon.lensFlare.js.map
  77257. "use strict";
  77258. var BABYLON;
  77259. (function (BABYLON) {
  77260. var LensFlareSystem = /** @class */ (function () {
  77261. function LensFlareSystem(name, emitter, scene) {
  77262. this.name = name;
  77263. this.lensFlares = new Array();
  77264. this.borderLimit = 300;
  77265. this.viewportBorder = 0;
  77266. this.layerMask = 0x0FFFFFFF;
  77267. this._vertexBuffers = {};
  77268. this._isEnabled = true;
  77269. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77270. this._emitter = emitter;
  77271. this.id = name;
  77272. scene.lensFlareSystems.push(this);
  77273. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  77274. var engine = scene.getEngine();
  77275. // VBO
  77276. var vertices = [];
  77277. vertices.push(1, 1);
  77278. vertices.push(-1, 1);
  77279. vertices.push(-1, -1);
  77280. vertices.push(1, -1);
  77281. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77282. // Indices
  77283. var indices = [];
  77284. indices.push(0);
  77285. indices.push(1);
  77286. indices.push(2);
  77287. indices.push(0);
  77288. indices.push(2);
  77289. indices.push(3);
  77290. this._indexBuffer = engine.createIndexBuffer(indices);
  77291. // Effects
  77292. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  77293. }
  77294. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  77295. get: function () {
  77296. return this._isEnabled;
  77297. },
  77298. set: function (value) {
  77299. this._isEnabled = value;
  77300. },
  77301. enumerable: true,
  77302. configurable: true
  77303. });
  77304. LensFlareSystem.prototype.getScene = function () {
  77305. return this._scene;
  77306. };
  77307. LensFlareSystem.prototype.getEmitter = function () {
  77308. return this._emitter;
  77309. };
  77310. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  77311. this._emitter = newEmitter;
  77312. };
  77313. LensFlareSystem.prototype.getEmitterPosition = function () {
  77314. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  77315. };
  77316. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  77317. var position = this.getEmitterPosition();
  77318. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  77319. this._positionX = position.x;
  77320. this._positionY = position.y;
  77321. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  77322. if (this.viewportBorder > 0) {
  77323. globalViewport.x -= this.viewportBorder;
  77324. globalViewport.y -= this.viewportBorder;
  77325. globalViewport.width += this.viewportBorder * 2;
  77326. globalViewport.height += this.viewportBorder * 2;
  77327. position.x += this.viewportBorder;
  77328. position.y += this.viewportBorder;
  77329. this._positionX += this.viewportBorder;
  77330. this._positionY += this.viewportBorder;
  77331. }
  77332. if (position.z > 0) {
  77333. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  77334. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  77335. return true;
  77336. }
  77337. return true;
  77338. }
  77339. return false;
  77340. };
  77341. LensFlareSystem.prototype._isVisible = function () {
  77342. if (!this._isEnabled || !this._scene.activeCamera) {
  77343. return false;
  77344. }
  77345. var emitterPosition = this.getEmitterPosition();
  77346. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77347. var distance = direction.length();
  77348. direction.normalize();
  77349. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77350. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77351. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77352. };
  77353. LensFlareSystem.prototype.render = function () {
  77354. if (!this._effect.isReady() || !this._scene.activeCamera)
  77355. return false;
  77356. var engine = this._scene.getEngine();
  77357. var viewport = this._scene.activeCamera.viewport;
  77358. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77359. // Position
  77360. if (!this.computeEffectivePosition(globalViewport)) {
  77361. return false;
  77362. }
  77363. // Visibility
  77364. if (!this._isVisible()) {
  77365. return false;
  77366. }
  77367. // Intensity
  77368. var awayX;
  77369. var awayY;
  77370. if (this._positionX < this.borderLimit + globalViewport.x) {
  77371. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77372. }
  77373. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77374. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77375. }
  77376. else {
  77377. awayX = 0;
  77378. }
  77379. if (this._positionY < this.borderLimit + globalViewport.y) {
  77380. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77381. }
  77382. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77383. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77384. }
  77385. else {
  77386. awayY = 0;
  77387. }
  77388. var away = (awayX > awayY) ? awayX : awayY;
  77389. away -= this.viewportBorder;
  77390. if (away > this.borderLimit) {
  77391. away = this.borderLimit;
  77392. }
  77393. var intensity = 1.0 - (away / this.borderLimit);
  77394. if (intensity < 0) {
  77395. return false;
  77396. }
  77397. if (intensity > 1.0) {
  77398. intensity = 1.0;
  77399. }
  77400. if (this.viewportBorder > 0) {
  77401. globalViewport.x += this.viewportBorder;
  77402. globalViewport.y += this.viewportBorder;
  77403. globalViewport.width -= this.viewportBorder * 2;
  77404. globalViewport.height -= this.viewportBorder * 2;
  77405. this._positionX -= this.viewportBorder;
  77406. this._positionY -= this.viewportBorder;
  77407. }
  77408. // Position
  77409. var centerX = globalViewport.x + globalViewport.width / 2;
  77410. var centerY = globalViewport.y + globalViewport.height / 2;
  77411. var distX = centerX - this._positionX;
  77412. var distY = centerY - this._positionY;
  77413. // Effects
  77414. engine.enableEffect(this._effect);
  77415. engine.setState(false);
  77416. engine.setDepthBuffer(false);
  77417. // VBOs
  77418. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77419. // Flares
  77420. for (var index = 0; index < this.lensFlares.length; index++) {
  77421. var flare = this.lensFlares[index];
  77422. engine.setAlphaMode(flare.alphaMode);
  77423. var x = centerX - (distX * flare.position);
  77424. var y = centerY - (distY * flare.position);
  77425. var cw = flare.size;
  77426. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77427. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77428. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77429. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77430. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77431. // Texture
  77432. this._effect.setTexture("textureSampler", flare.texture);
  77433. // Color
  77434. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77435. // Draw order
  77436. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77437. }
  77438. engine.setDepthBuffer(true);
  77439. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77440. return true;
  77441. };
  77442. LensFlareSystem.prototype.dispose = function () {
  77443. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77444. if (vertexBuffer) {
  77445. vertexBuffer.dispose();
  77446. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77447. }
  77448. if (this._indexBuffer) {
  77449. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77450. this._indexBuffer = null;
  77451. }
  77452. while (this.lensFlares.length) {
  77453. this.lensFlares[0].dispose();
  77454. }
  77455. // Remove from scene
  77456. var index = this._scene.lensFlareSystems.indexOf(this);
  77457. this._scene.lensFlareSystems.splice(index, 1);
  77458. };
  77459. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77460. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77461. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77462. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77463. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77464. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77465. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77466. var parsedFlare = parsedLensFlareSystem.flares[index];
  77467. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77468. }
  77469. return lensFlareSystem;
  77470. };
  77471. LensFlareSystem.prototype.serialize = function () {
  77472. var serializationObject = {};
  77473. serializationObject.id = this.id;
  77474. serializationObject.name = this.name;
  77475. serializationObject.emitterId = this.getEmitter().id;
  77476. serializationObject.borderLimit = this.borderLimit;
  77477. serializationObject.flares = [];
  77478. for (var index = 0; index < this.lensFlares.length; index++) {
  77479. var flare = this.lensFlares[index];
  77480. serializationObject.flares.push({
  77481. size: flare.size,
  77482. position: flare.position,
  77483. color: flare.color.asArray(),
  77484. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77485. });
  77486. }
  77487. return serializationObject;
  77488. };
  77489. return LensFlareSystem;
  77490. }());
  77491. BABYLON.LensFlareSystem = LensFlareSystem;
  77492. })(BABYLON || (BABYLON = {}));
  77493. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77494. "use strict";
  77495. var BABYLON;
  77496. (function (BABYLON) {
  77497. /**
  77498. * This is a holder class for the physics joint created by the physics plugin.
  77499. * It holds a set of functions to control the underlying joint.
  77500. */
  77501. var PhysicsJoint = /** @class */ (function () {
  77502. function PhysicsJoint(type, jointData) {
  77503. this.type = type;
  77504. this.jointData = jointData;
  77505. jointData.nativeParams = jointData.nativeParams || {};
  77506. }
  77507. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77508. get: function () {
  77509. return this._physicsJoint;
  77510. },
  77511. set: function (newJoint) {
  77512. if (this._physicsJoint) {
  77513. //remove from the wolrd
  77514. }
  77515. this._physicsJoint = newJoint;
  77516. },
  77517. enumerable: true,
  77518. configurable: true
  77519. });
  77520. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77521. set: function (physicsPlugin) {
  77522. this._physicsPlugin = physicsPlugin;
  77523. },
  77524. enumerable: true,
  77525. configurable: true
  77526. });
  77527. /**
  77528. * Execute a function that is physics-plugin specific.
  77529. * @param {Function} func the function that will be executed.
  77530. * It accepts two parameters: the physics world and the physics joint.
  77531. */
  77532. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77533. func(this._physicsPlugin.world, this._physicsJoint);
  77534. };
  77535. //TODO check if the native joints are the same
  77536. //Joint Types
  77537. PhysicsJoint.DistanceJoint = 0;
  77538. PhysicsJoint.HingeJoint = 1;
  77539. PhysicsJoint.BallAndSocketJoint = 2;
  77540. PhysicsJoint.WheelJoint = 3;
  77541. PhysicsJoint.SliderJoint = 4;
  77542. //OIMO
  77543. PhysicsJoint.PrismaticJoint = 5;
  77544. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77545. PhysicsJoint.UniversalJoint = 6;
  77546. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77547. //Cannon
  77548. //Similar to a Ball-Joint. Different in params
  77549. PhysicsJoint.PointToPointJoint = 8;
  77550. //Cannon only at the moment
  77551. PhysicsJoint.SpringJoint = 9;
  77552. PhysicsJoint.LockJoint = 10;
  77553. return PhysicsJoint;
  77554. }());
  77555. BABYLON.PhysicsJoint = PhysicsJoint;
  77556. /**
  77557. * A class representing a physics distance joint.
  77558. */
  77559. var DistanceJoint = /** @class */ (function (_super) {
  77560. __extends(DistanceJoint, _super);
  77561. function DistanceJoint(jointData) {
  77562. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77563. }
  77564. /**
  77565. * Update the predefined distance.
  77566. */
  77567. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77568. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77569. };
  77570. return DistanceJoint;
  77571. }(PhysicsJoint));
  77572. BABYLON.DistanceJoint = DistanceJoint;
  77573. var MotorEnabledJoint = /** @class */ (function (_super) {
  77574. __extends(MotorEnabledJoint, _super);
  77575. function MotorEnabledJoint(type, jointData) {
  77576. return _super.call(this, type, jointData) || this;
  77577. }
  77578. /**
  77579. * Set the motor values.
  77580. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77581. * @param {number} force the force to apply
  77582. * @param {number} maxForce max force for this motor.
  77583. */
  77584. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77585. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77586. };
  77587. /**
  77588. * Set the motor's limits.
  77589. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77590. */
  77591. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77592. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77593. };
  77594. return MotorEnabledJoint;
  77595. }(PhysicsJoint));
  77596. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77597. /**
  77598. * This class represents a single hinge physics joint
  77599. */
  77600. var HingeJoint = /** @class */ (function (_super) {
  77601. __extends(HingeJoint, _super);
  77602. function HingeJoint(jointData) {
  77603. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77604. }
  77605. /**
  77606. * Set the motor values.
  77607. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77608. * @param {number} force the force to apply
  77609. * @param {number} maxForce max force for this motor.
  77610. */
  77611. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77612. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77613. };
  77614. /**
  77615. * Set the motor's limits.
  77616. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77617. */
  77618. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77619. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77620. };
  77621. return HingeJoint;
  77622. }(MotorEnabledJoint));
  77623. BABYLON.HingeJoint = HingeJoint;
  77624. /**
  77625. * This class represents a dual hinge physics joint (same as wheel joint)
  77626. */
  77627. var Hinge2Joint = /** @class */ (function (_super) {
  77628. __extends(Hinge2Joint, _super);
  77629. function Hinge2Joint(jointData) {
  77630. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77631. }
  77632. /**
  77633. * Set the motor values.
  77634. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77635. * @param {number} force the force to apply
  77636. * @param {number} maxForce max force for this motor.
  77637. * @param {motorIndex} the motor's index, 0 or 1.
  77638. */
  77639. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77640. if (motorIndex === void 0) { motorIndex = 0; }
  77641. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77642. };
  77643. /**
  77644. * Set the motor limits.
  77645. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77646. * @param {number} upperLimit the upper limit
  77647. * @param {number} lowerLimit lower limit
  77648. * @param {motorIndex} the motor's index, 0 or 1.
  77649. */
  77650. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77651. if (motorIndex === void 0) { motorIndex = 0; }
  77652. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77653. };
  77654. return Hinge2Joint;
  77655. }(MotorEnabledJoint));
  77656. BABYLON.Hinge2Joint = Hinge2Joint;
  77657. })(BABYLON || (BABYLON = {}));
  77658. //# sourceMappingURL=babylon.physicsJoint.js.map
  77659. "use strict";
  77660. var BABYLON;
  77661. (function (BABYLON) {
  77662. var PhysicsImpostor = /** @class */ (function () {
  77663. function PhysicsImpostor(object, type, _options, _scene) {
  77664. if (_options === void 0) { _options = { mass: 0 }; }
  77665. var _this = this;
  77666. this.object = object;
  77667. this.type = type;
  77668. this._options = _options;
  77669. this._scene = _scene;
  77670. this._bodyUpdateRequired = false;
  77671. this._onBeforePhysicsStepCallbacks = new Array();
  77672. this._onAfterPhysicsStepCallbacks = new Array();
  77673. this._onPhysicsCollideCallbacks = [];
  77674. this._deltaPosition = BABYLON.Vector3.Zero();
  77675. this._isDisposed = false;
  77676. //temp variables for parent rotation calculations
  77677. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77678. this._tmpQuat = new BABYLON.Quaternion();
  77679. this._tmpQuat2 = new BABYLON.Quaternion();
  77680. /**
  77681. * this function is executed by the physics engine.
  77682. */
  77683. this.beforeStep = function () {
  77684. if (!_this._physicsEngine) {
  77685. return;
  77686. }
  77687. _this.object.translate(_this._deltaPosition, -1);
  77688. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77689. _this.object.computeWorldMatrix(false);
  77690. if (_this.object.parent && _this.object.rotationQuaternion) {
  77691. _this.getParentsRotation();
  77692. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77693. }
  77694. else {
  77695. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77696. }
  77697. if (!_this._options.disableBidirectionalTransformation) {
  77698. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77699. }
  77700. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77701. func(_this);
  77702. });
  77703. };
  77704. /**
  77705. * this function is executed by the physics engine.
  77706. */
  77707. this.afterStep = function () {
  77708. if (!_this._physicsEngine) {
  77709. return;
  77710. }
  77711. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77712. func(_this);
  77713. });
  77714. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77715. // object has now its world rotation. needs to be converted to local.
  77716. if (_this.object.parent && _this.object.rotationQuaternion) {
  77717. _this.getParentsRotation();
  77718. _this._tmpQuat.conjugateInPlace();
  77719. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77720. }
  77721. // take the position set and make it the absolute position of this object.
  77722. _this.object.setAbsolutePosition(_this.object.position);
  77723. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77724. _this.object.translate(_this._deltaPosition, 1);
  77725. };
  77726. /**
  77727. * Legacy collision detection event support
  77728. */
  77729. this.onCollideEvent = null;
  77730. //event and body object due to cannon's event-based architecture.
  77731. this.onCollide = function (e) {
  77732. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77733. return;
  77734. }
  77735. if (!_this._physicsEngine) {
  77736. return;
  77737. }
  77738. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77739. if (otherImpostor) {
  77740. // Legacy collision detection event support
  77741. if (_this.onCollideEvent) {
  77742. _this.onCollideEvent(_this, otherImpostor);
  77743. }
  77744. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77745. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77746. }).forEach(function (obj) {
  77747. obj.callback(_this, otherImpostor);
  77748. });
  77749. }
  77750. };
  77751. //sanity check!
  77752. if (!this.object) {
  77753. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77754. return;
  77755. }
  77756. //legacy support for old syntax.
  77757. if (!this._scene && object.getScene) {
  77758. this._scene = object.getScene();
  77759. }
  77760. if (!this._scene) {
  77761. return;
  77762. }
  77763. this._physicsEngine = this._scene.getPhysicsEngine();
  77764. if (!this._physicsEngine) {
  77765. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77766. }
  77767. else {
  77768. //set the object's quaternion, if not set
  77769. if (!this.object.rotationQuaternion) {
  77770. if (this.object.rotation) {
  77771. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77772. }
  77773. else {
  77774. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77775. }
  77776. }
  77777. //default options params
  77778. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77779. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77780. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77781. this._joints = [];
  77782. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77783. if (!this.object.parent || this._options.ignoreParent) {
  77784. this._init();
  77785. }
  77786. else if (this.object.parent.physicsImpostor) {
  77787. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77788. }
  77789. }
  77790. }
  77791. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77792. get: function () {
  77793. return this._isDisposed;
  77794. },
  77795. enumerable: true,
  77796. configurable: true
  77797. });
  77798. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77799. get: function () {
  77800. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77801. },
  77802. set: function (value) {
  77803. this.setMass(value);
  77804. },
  77805. enumerable: true,
  77806. configurable: true
  77807. });
  77808. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77809. get: function () {
  77810. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77811. },
  77812. set: function (value) {
  77813. if (!this._physicsEngine) {
  77814. return;
  77815. }
  77816. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77817. },
  77818. enumerable: true,
  77819. configurable: true
  77820. });
  77821. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77822. get: function () {
  77823. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77824. },
  77825. set: function (value) {
  77826. if (!this._physicsEngine) {
  77827. return;
  77828. }
  77829. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77830. },
  77831. enumerable: true,
  77832. configurable: true
  77833. });
  77834. /**
  77835. * This function will completly initialize this impostor.
  77836. * It will create a new body - but only if this mesh has no parent.
  77837. * If it has, this impostor will not be used other than to define the impostor
  77838. * of the child mesh.
  77839. */
  77840. PhysicsImpostor.prototype._init = function () {
  77841. if (!this._physicsEngine) {
  77842. return;
  77843. }
  77844. this._physicsEngine.removeImpostor(this);
  77845. this.physicsBody = null;
  77846. this._parent = this._parent || this._getPhysicsParent();
  77847. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77848. this._physicsEngine.addImpostor(this);
  77849. }
  77850. };
  77851. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77852. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77853. var parentMesh = this.object.parent;
  77854. return parentMesh.physicsImpostor;
  77855. }
  77856. return null;
  77857. };
  77858. /**
  77859. * Should a new body be generated.
  77860. */
  77861. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77862. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77863. };
  77864. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77865. this.forceUpdate();
  77866. };
  77867. /**
  77868. * Force a regeneration of this or the parent's impostor's body.
  77869. * Use under cautious - This will remove all joints already implemented.
  77870. */
  77871. PhysicsImpostor.prototype.forceUpdate = function () {
  77872. this._init();
  77873. if (this.parent && !this._options.ignoreParent) {
  77874. this.parent.forceUpdate();
  77875. }
  77876. };
  77877. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77878. /*public get mesh(): AbstractMesh {
  77879. return this._mesh;
  77880. }*/
  77881. /**
  77882. * Gets the body that holds this impostor. Either its own, or its parent.
  77883. */
  77884. get: function () {
  77885. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77886. },
  77887. /**
  77888. * Set the physics body. Used mainly by the physics engine/plugin
  77889. */
  77890. set: function (physicsBody) {
  77891. if (this._physicsBody && this._physicsEngine) {
  77892. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77893. }
  77894. this._physicsBody = physicsBody;
  77895. this.resetUpdateFlags();
  77896. },
  77897. enumerable: true,
  77898. configurable: true
  77899. });
  77900. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77901. get: function () {
  77902. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77903. },
  77904. set: function (value) {
  77905. this._parent = value;
  77906. },
  77907. enumerable: true,
  77908. configurable: true
  77909. });
  77910. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77911. this._bodyUpdateRequired = false;
  77912. };
  77913. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77914. if (this.object.getBoundingInfo) {
  77915. var q = this.object.rotationQuaternion;
  77916. //reset rotation
  77917. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77918. //calculate the world matrix with no rotation
  77919. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77920. var boundingInfo = this.object.getBoundingInfo();
  77921. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77922. //bring back the rotation
  77923. this.object.rotationQuaternion = q;
  77924. //calculate the world matrix with the new rotation
  77925. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77926. return size;
  77927. }
  77928. else {
  77929. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77930. }
  77931. };
  77932. PhysicsImpostor.prototype.getObjectCenter = function () {
  77933. if (this.object.getBoundingInfo) {
  77934. var boundingInfo = this.object.getBoundingInfo();
  77935. return boundingInfo.boundingBox.centerWorld;
  77936. }
  77937. else {
  77938. return this.object.position;
  77939. }
  77940. };
  77941. /**
  77942. * Get a specific parametes from the options parameter.
  77943. */
  77944. PhysicsImpostor.prototype.getParam = function (paramName) {
  77945. return this._options[paramName];
  77946. };
  77947. /**
  77948. * Sets a specific parameter in the options given to the physics plugin
  77949. */
  77950. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77951. this._options[paramName] = value;
  77952. this._bodyUpdateRequired = true;
  77953. };
  77954. /**
  77955. * Specifically change the body's mass option. Won't recreate the physics body object
  77956. */
  77957. PhysicsImpostor.prototype.setMass = function (mass) {
  77958. if (this.getParam("mass") !== mass) {
  77959. this.setParam("mass", mass);
  77960. }
  77961. if (this._physicsEngine) {
  77962. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77963. }
  77964. };
  77965. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77966. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77967. };
  77968. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77969. if (this._physicsEngine) {
  77970. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77971. }
  77972. };
  77973. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77974. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77975. };
  77976. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77977. if (this._physicsEngine) {
  77978. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77979. }
  77980. };
  77981. /**
  77982. * Execute a function with the physics plugin native code.
  77983. * Provide a function the will have two variables - the world object and the physics body object.
  77984. */
  77985. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77986. if (this._physicsEngine) {
  77987. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77988. }
  77989. };
  77990. /**
  77991. * Register a function that will be executed before the physics world is stepping forward.
  77992. */
  77993. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77994. this._onBeforePhysicsStepCallbacks.push(func);
  77995. };
  77996. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77997. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77998. if (index > -1) {
  77999. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  78000. }
  78001. else {
  78002. BABYLON.Tools.Warn("Function to remove was not found");
  78003. }
  78004. };
  78005. /**
  78006. * Register a function that will be executed after the physics step
  78007. */
  78008. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  78009. this._onAfterPhysicsStepCallbacks.push(func);
  78010. };
  78011. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  78012. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  78013. if (index > -1) {
  78014. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  78015. }
  78016. else {
  78017. BABYLON.Tools.Warn("Function to remove was not found");
  78018. }
  78019. };
  78020. /**
  78021. * register a function that will be executed when this impostor collides against a different body.
  78022. */
  78023. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  78024. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  78025. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  78026. };
  78027. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  78028. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  78029. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  78030. if (index > -1) {
  78031. this._onPhysicsCollideCallbacks.splice(index, 1);
  78032. }
  78033. else {
  78034. BABYLON.Tools.Warn("Function to remove was not found");
  78035. }
  78036. };
  78037. PhysicsImpostor.prototype.getParentsRotation = function () {
  78038. var parent = this.object.parent;
  78039. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  78040. while (parent) {
  78041. if (parent.rotationQuaternion) {
  78042. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  78043. }
  78044. else {
  78045. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  78046. }
  78047. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  78048. parent = parent.parent;
  78049. }
  78050. return this._tmpQuat;
  78051. };
  78052. /**
  78053. * Apply a force
  78054. */
  78055. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  78056. if (this._physicsEngine) {
  78057. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  78058. }
  78059. return this;
  78060. };
  78061. /**
  78062. * Apply an impulse
  78063. */
  78064. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  78065. if (this._physicsEngine) {
  78066. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  78067. }
  78068. return this;
  78069. };
  78070. /**
  78071. * A help function to create a joint.
  78072. */
  78073. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  78074. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  78075. this.addJoint(otherImpostor, joint);
  78076. return this;
  78077. };
  78078. /**
  78079. * Add a joint to this impostor with a different impostor.
  78080. */
  78081. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  78082. this._joints.push({
  78083. otherImpostor: otherImpostor,
  78084. joint: joint
  78085. });
  78086. if (this._physicsEngine) {
  78087. this._physicsEngine.addJoint(this, otherImpostor, joint);
  78088. }
  78089. return this;
  78090. };
  78091. /**
  78092. * Will keep this body still, in a sleep mode.
  78093. */
  78094. PhysicsImpostor.prototype.sleep = function () {
  78095. if (this._physicsEngine) {
  78096. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  78097. }
  78098. return this;
  78099. };
  78100. /**
  78101. * Wake the body up.
  78102. */
  78103. PhysicsImpostor.prototype.wakeUp = function () {
  78104. if (this._physicsEngine) {
  78105. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  78106. }
  78107. return this;
  78108. };
  78109. PhysicsImpostor.prototype.clone = function (newObject) {
  78110. if (!newObject)
  78111. return null;
  78112. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  78113. };
  78114. PhysicsImpostor.prototype.dispose = function () {
  78115. var _this = this;
  78116. //no dispose if no physics engine is available.
  78117. if (!this._physicsEngine) {
  78118. return;
  78119. }
  78120. this._joints.forEach(function (j) {
  78121. if (_this._physicsEngine) {
  78122. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  78123. }
  78124. });
  78125. //dispose the physics body
  78126. this._physicsEngine.removeImpostor(this);
  78127. if (this.parent) {
  78128. this.parent.forceUpdate();
  78129. }
  78130. else {
  78131. /*this._object.getChildMeshes().forEach(function(mesh) {
  78132. if (mesh.physicsImpostor) {
  78133. if (disposeChildren) {
  78134. mesh.physicsImpostor.dispose();
  78135. mesh.physicsImpostor = null;
  78136. }
  78137. }
  78138. })*/
  78139. }
  78140. this._isDisposed = true;
  78141. };
  78142. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  78143. this._deltaPosition.copyFrom(position);
  78144. };
  78145. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  78146. if (!this._deltaRotation) {
  78147. this._deltaRotation = new BABYLON.Quaternion();
  78148. }
  78149. this._deltaRotation.copyFrom(rotation);
  78150. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  78151. };
  78152. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  78153. if (this._physicsEngine) {
  78154. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  78155. }
  78156. return this;
  78157. };
  78158. PhysicsImpostor.prototype.getRadius = function () {
  78159. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  78160. };
  78161. /**
  78162. * Sync a bone with this impostor
  78163. * @param bone The bone to sync to the impostor.
  78164. * @param boneMesh The mesh that the bone is influencing.
  78165. * @param jointPivot The pivot of the joint / bone in local space.
  78166. * @param distToJoint Optional distance from the impostor to the joint.
  78167. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  78168. */
  78169. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  78170. var tempVec = PhysicsImpostor._tmpVecs[0];
  78171. var mesh = this.object;
  78172. if (mesh.rotationQuaternion) {
  78173. if (adjustRotation) {
  78174. var tempQuat = PhysicsImpostor._tmpQuat;
  78175. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  78176. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  78177. }
  78178. else {
  78179. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  78180. }
  78181. }
  78182. tempVec.x = 0;
  78183. tempVec.y = 0;
  78184. tempVec.z = 0;
  78185. if (jointPivot) {
  78186. tempVec.x = jointPivot.x;
  78187. tempVec.y = jointPivot.y;
  78188. tempVec.z = jointPivot.z;
  78189. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  78190. if (distToJoint === undefined || distToJoint === null) {
  78191. distToJoint = jointPivot.length();
  78192. }
  78193. tempVec.x *= distToJoint;
  78194. tempVec.y *= distToJoint;
  78195. tempVec.z *= distToJoint;
  78196. }
  78197. if (bone.getParent()) {
  78198. tempVec.addInPlace(mesh.getAbsolutePosition());
  78199. bone.setAbsolutePosition(tempVec, boneMesh);
  78200. }
  78201. else {
  78202. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  78203. boneMesh.position.x -= tempVec.x;
  78204. boneMesh.position.y -= tempVec.y;
  78205. boneMesh.position.z -= tempVec.z;
  78206. }
  78207. };
  78208. /**
  78209. * Sync impostor to a bone
  78210. * @param bone The bone that the impostor will be synced to.
  78211. * @param boneMesh The mesh that the bone is influencing.
  78212. * @param jointPivot The pivot of the joint / bone in local space.
  78213. * @param distToJoint Optional distance from the impostor to the joint.
  78214. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  78215. * @param boneAxis Optional vector3 axis the bone is aligned with
  78216. */
  78217. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  78218. var mesh = this.object;
  78219. if (mesh.rotationQuaternion) {
  78220. if (adjustRotation) {
  78221. var tempQuat = PhysicsImpostor._tmpQuat;
  78222. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  78223. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  78224. }
  78225. else {
  78226. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  78227. }
  78228. }
  78229. var pos = PhysicsImpostor._tmpVecs[0];
  78230. var boneDir = PhysicsImpostor._tmpVecs[1];
  78231. if (!boneAxis) {
  78232. boneAxis = PhysicsImpostor._tmpVecs[2];
  78233. boneAxis.x = 0;
  78234. boneAxis.y = 1;
  78235. boneAxis.z = 0;
  78236. }
  78237. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  78238. bone.getAbsolutePositionToRef(boneMesh, pos);
  78239. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  78240. distToJoint = jointPivot.length();
  78241. }
  78242. if (distToJoint !== undefined && distToJoint !== null) {
  78243. pos.x += boneDir.x * distToJoint;
  78244. pos.y += boneDir.y * distToJoint;
  78245. pos.z += boneDir.z * distToJoint;
  78246. }
  78247. mesh.setAbsolutePosition(pos);
  78248. };
  78249. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  78250. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  78251. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78252. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  78253. //Impostor types
  78254. PhysicsImpostor.NoImpostor = 0;
  78255. PhysicsImpostor.SphereImpostor = 1;
  78256. PhysicsImpostor.BoxImpostor = 2;
  78257. PhysicsImpostor.PlaneImpostor = 3;
  78258. PhysicsImpostor.MeshImpostor = 4;
  78259. PhysicsImpostor.CylinderImpostor = 7;
  78260. PhysicsImpostor.ParticleImpostor = 8;
  78261. PhysicsImpostor.HeightmapImpostor = 9;
  78262. return PhysicsImpostor;
  78263. }());
  78264. BABYLON.PhysicsImpostor = PhysicsImpostor;
  78265. })(BABYLON || (BABYLON = {}));
  78266. //# sourceMappingURL=babylon.physicsImpostor.js.map
  78267. "use strict";
  78268. var BABYLON;
  78269. (function (BABYLON) {
  78270. var PhysicsEngine = /** @class */ (function () {
  78271. function PhysicsEngine(gravity, _physicsPlugin) {
  78272. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  78273. this._physicsPlugin = _physicsPlugin;
  78274. //new methods and parameters
  78275. this._impostors = [];
  78276. this._joints = [];
  78277. if (!this._physicsPlugin.isSupported()) {
  78278. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  78279. + "Please make sure it is included.");
  78280. }
  78281. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  78282. this.setGravity(gravity);
  78283. this.setTimeStep();
  78284. }
  78285. PhysicsEngine.prototype.setGravity = function (gravity) {
  78286. this.gravity = gravity;
  78287. this._physicsPlugin.setGravity(this.gravity);
  78288. };
  78289. /**
  78290. * Set the time step of the physics engine.
  78291. * default is 1/60.
  78292. * To slow it down, enter 1/600 for example.
  78293. * To speed it up, 1/30
  78294. * @param {number} newTimeStep the new timestep to apply to this world.
  78295. */
  78296. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  78297. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  78298. this._physicsPlugin.setTimeStep(newTimeStep);
  78299. };
  78300. /**
  78301. * Get the time step of the physics engine.
  78302. */
  78303. PhysicsEngine.prototype.getTimeStep = function () {
  78304. return this._physicsPlugin.getTimeStep();
  78305. };
  78306. PhysicsEngine.prototype.dispose = function () {
  78307. this._impostors.forEach(function (impostor) {
  78308. impostor.dispose();
  78309. });
  78310. this._physicsPlugin.dispose();
  78311. };
  78312. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  78313. return this._physicsPlugin.name;
  78314. };
  78315. /**
  78316. * Adding a new impostor for the impostor tracking.
  78317. * This will be done by the impostor itself.
  78318. * @param {PhysicsImpostor} impostor the impostor to add
  78319. */
  78320. PhysicsEngine.prototype.addImpostor = function (impostor) {
  78321. impostor.uniqueId = this._impostors.push(impostor);
  78322. //if no parent, generate the body
  78323. if (!impostor.parent) {
  78324. this._physicsPlugin.generatePhysicsBody(impostor);
  78325. }
  78326. };
  78327. /**
  78328. * Remove an impostor from the engine.
  78329. * This impostor and its mesh will not longer be updated by the physics engine.
  78330. * @param {PhysicsImpostor} impostor the impostor to remove
  78331. */
  78332. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  78333. var index = this._impostors.indexOf(impostor);
  78334. if (index > -1) {
  78335. var removed = this._impostors.splice(index, 1);
  78336. //Is it needed?
  78337. if (removed.length) {
  78338. //this will also remove it from the world.
  78339. removed[0].physicsBody = null;
  78340. }
  78341. }
  78342. };
  78343. /**
  78344. * Add a joint to the physics engine
  78345. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78346. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78347. * @param {PhysicsJoint} the joint that will connect both impostors.
  78348. */
  78349. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78350. var impostorJoint = {
  78351. mainImpostor: mainImpostor,
  78352. connectedImpostor: connectedImpostor,
  78353. joint: joint
  78354. };
  78355. joint.physicsPlugin = this._physicsPlugin;
  78356. this._joints.push(impostorJoint);
  78357. this._physicsPlugin.generateJoint(impostorJoint);
  78358. };
  78359. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78360. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78361. return (impostorJoint.connectedImpostor === connectedImpostor
  78362. && impostorJoint.joint === joint
  78363. && impostorJoint.mainImpostor === mainImpostor);
  78364. });
  78365. if (matchingJoints.length) {
  78366. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78367. //TODO remove it from the list as well
  78368. }
  78369. };
  78370. /**
  78371. * Called by the scene. no need to call it.
  78372. */
  78373. PhysicsEngine.prototype._step = function (delta) {
  78374. var _this = this;
  78375. //check if any mesh has no body / requires an update
  78376. this._impostors.forEach(function (impostor) {
  78377. if (impostor.isBodyInitRequired()) {
  78378. _this._physicsPlugin.generatePhysicsBody(impostor);
  78379. }
  78380. });
  78381. if (delta > 0.1) {
  78382. delta = 0.1;
  78383. }
  78384. else if (delta <= 0) {
  78385. delta = 1.0 / 60.0;
  78386. }
  78387. this._physicsPlugin.executeStep(delta, this._impostors);
  78388. };
  78389. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78390. return this._physicsPlugin;
  78391. };
  78392. PhysicsEngine.prototype.getImpostors = function () {
  78393. return this._impostors;
  78394. };
  78395. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78396. for (var i = 0; i < this._impostors.length; ++i) {
  78397. if (this._impostors[i].object === object) {
  78398. return this._impostors[i];
  78399. }
  78400. }
  78401. return null;
  78402. };
  78403. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78404. for (var i = 0; i < this._impostors.length; ++i) {
  78405. if (this._impostors[i].physicsBody === body) {
  78406. return this._impostors[i];
  78407. }
  78408. }
  78409. return null;
  78410. };
  78411. // Statics
  78412. PhysicsEngine.Epsilon = 0.001;
  78413. return PhysicsEngine;
  78414. }());
  78415. BABYLON.PhysicsEngine = PhysicsEngine;
  78416. })(BABYLON || (BABYLON = {}));
  78417. //# sourceMappingURL=babylon.physicsEngine.js.map
  78418. "use strict";
  78419. var BABYLON;
  78420. (function (BABYLON) {
  78421. var PhysicsHelper = /** @class */ (function () {
  78422. function PhysicsHelper(scene) {
  78423. this._scene = scene;
  78424. this._physicsEngine = this._scene.getPhysicsEngine();
  78425. if (!this._physicsEngine) {
  78426. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78427. }
  78428. }
  78429. /**
  78430. * @param {Vector3} origin the origin of the explosion
  78431. * @param {number} radius the explosion radius
  78432. * @param {number} strength the explosion strength
  78433. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78434. */
  78435. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78436. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78437. if (!this._physicsEngine) {
  78438. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78439. return null;
  78440. }
  78441. var impostors = this._physicsEngine.getImpostors();
  78442. if (impostors.length === 0) {
  78443. return null;
  78444. }
  78445. var event = new PhysicsRadialExplosionEvent(this._scene);
  78446. impostors.forEach(function (impostor) {
  78447. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78448. if (!impostorForceAndContactPoint) {
  78449. return;
  78450. }
  78451. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78452. });
  78453. event.dispose(false);
  78454. return event;
  78455. };
  78456. /**
  78457. * @param {Vector3} origin the origin of the explosion
  78458. * @param {number} radius the explosion radius
  78459. * @param {number} strength the explosion strength
  78460. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78461. */
  78462. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78463. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78464. if (!this._physicsEngine) {
  78465. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78466. return null;
  78467. }
  78468. var impostors = this._physicsEngine.getImpostors();
  78469. if (impostors.length === 0) {
  78470. return null;
  78471. }
  78472. var event = new PhysicsRadialExplosionEvent(this._scene);
  78473. impostors.forEach(function (impostor) {
  78474. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78475. if (!impostorForceAndContactPoint) {
  78476. return;
  78477. }
  78478. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78479. });
  78480. event.dispose(false);
  78481. return event;
  78482. };
  78483. /**
  78484. * @param {Vector3} origin the origin of the explosion
  78485. * @param {number} radius the explosion radius
  78486. * @param {number} strength the explosion strength
  78487. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78488. */
  78489. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78490. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78491. if (!this._physicsEngine) {
  78492. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78493. return null;
  78494. }
  78495. var impostors = this._physicsEngine.getImpostors();
  78496. if (impostors.length === 0) {
  78497. return null;
  78498. }
  78499. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78500. event.dispose(false);
  78501. return event;
  78502. };
  78503. /**
  78504. * @param {Vector3} origin the origin of the updraft
  78505. * @param {number} radius the radius of the updraft
  78506. * @param {number} strength the strength of the updraft
  78507. * @param {number} height the height of the updraft
  78508. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78509. */
  78510. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78511. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78512. if (!this._physicsEngine) {
  78513. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78514. return null;
  78515. }
  78516. if (this._physicsEngine.getImpostors().length === 0) {
  78517. return null;
  78518. }
  78519. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78520. event.dispose(false);
  78521. return event;
  78522. };
  78523. /**
  78524. * @param {Vector3} origin the of the vortex
  78525. * @param {number} radius the radius of the vortex
  78526. * @param {number} strength the strength of the vortex
  78527. * @param {number} height the height of the vortex
  78528. */
  78529. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78530. if (!this._physicsEngine) {
  78531. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78532. return null;
  78533. }
  78534. if (this._physicsEngine.getImpostors().length === 0) {
  78535. return null;
  78536. }
  78537. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78538. event.dispose(false);
  78539. return event;
  78540. };
  78541. return PhysicsHelper;
  78542. }());
  78543. BABYLON.PhysicsHelper = PhysicsHelper;
  78544. /***** Radial explosion *****/
  78545. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78546. function PhysicsRadialExplosionEvent(scene) {
  78547. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78548. this._rays = [];
  78549. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78550. this._scene = scene;
  78551. }
  78552. /**
  78553. * Returns the data related to the radial explosion event (sphere & rays).
  78554. * @returns {PhysicsRadialExplosionEventData}
  78555. */
  78556. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78557. this._dataFetched = true;
  78558. return {
  78559. sphere: this._sphere,
  78560. rays: this._rays,
  78561. };
  78562. };
  78563. /**
  78564. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78565. * @param impostor
  78566. * @param {Vector3} origin the origin of the explosion
  78567. * @param {number} radius the explosion radius
  78568. * @param {number} strength the explosion strength
  78569. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78570. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78571. */
  78572. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78573. if (impostor.mass === 0) {
  78574. return null;
  78575. }
  78576. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78577. return null;
  78578. }
  78579. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78580. return null;
  78581. }
  78582. var impostorObjectCenter = impostor.getObjectCenter();
  78583. var direction = impostorObjectCenter.subtract(origin);
  78584. var ray = new BABYLON.Ray(origin, direction, radius);
  78585. this._rays.push(ray);
  78586. var hit = ray.intersectsMesh(impostor.object);
  78587. var contactPoint = hit.pickedPoint;
  78588. if (!contactPoint) {
  78589. return null;
  78590. }
  78591. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78592. if (distanceFromOrigin > radius) {
  78593. return null;
  78594. }
  78595. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78596. ? strength
  78597. : strength * (1 - (distanceFromOrigin / radius));
  78598. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78599. return { force: force, contactPoint: contactPoint };
  78600. };
  78601. /**
  78602. * Disposes the sphere.
  78603. * @param {bolean} force
  78604. */
  78605. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78606. var _this = this;
  78607. if (force === void 0) { force = true; }
  78608. if (force) {
  78609. this._sphere.dispose();
  78610. }
  78611. else {
  78612. setTimeout(function () {
  78613. if (!_this._dataFetched) {
  78614. _this._sphere.dispose();
  78615. }
  78616. }, 0);
  78617. }
  78618. };
  78619. /*** Helpers ***/
  78620. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78621. if (!this._sphere) {
  78622. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78623. this._sphere.isVisible = false;
  78624. }
  78625. };
  78626. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78627. var impostorObject = impostor.object;
  78628. this._prepareSphere();
  78629. this._sphere.position = origin;
  78630. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78631. this._sphere._updateBoundingInfo();
  78632. this._sphere.computeWorldMatrix(true);
  78633. return this._sphere.intersectsMesh(impostorObject, true);
  78634. };
  78635. return PhysicsRadialExplosionEvent;
  78636. }());
  78637. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78638. /***** Gravitational Field *****/
  78639. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78640. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78641. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78642. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78643. this._physicsHelper = physicsHelper;
  78644. this._scene = scene;
  78645. this._origin = origin;
  78646. this._radius = radius;
  78647. this._strength = strength;
  78648. this._falloff = falloff;
  78649. this._tickCallback = this._tick.bind(this);
  78650. }
  78651. /**
  78652. * Returns the data related to the gravitational field event (sphere).
  78653. * @returns {PhysicsGravitationalFieldEventData}
  78654. */
  78655. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78656. this._dataFetched = true;
  78657. return {
  78658. sphere: this._sphere,
  78659. };
  78660. };
  78661. /**
  78662. * Enables the gravitational field.
  78663. */
  78664. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78665. this._tickCallback.call(this);
  78666. this._scene.registerBeforeRender(this._tickCallback);
  78667. };
  78668. /**
  78669. * Disables the gravitational field.
  78670. */
  78671. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78672. this._scene.unregisterBeforeRender(this._tickCallback);
  78673. };
  78674. /**
  78675. * Disposes the sphere.
  78676. * @param {bolean} force
  78677. */
  78678. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78679. var _this = this;
  78680. if (force === void 0) { force = true; }
  78681. if (force) {
  78682. this._sphere.dispose();
  78683. }
  78684. else {
  78685. setTimeout(function () {
  78686. if (!_this._dataFetched) {
  78687. _this._sphere.dispose();
  78688. }
  78689. }, 0);
  78690. }
  78691. };
  78692. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78693. // Since the params won't change, we fetch the event only once
  78694. if (this._sphere) {
  78695. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78696. }
  78697. else {
  78698. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78699. if (radialExplosionEvent) {
  78700. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78701. }
  78702. }
  78703. };
  78704. return PhysicsGravitationalFieldEvent;
  78705. }());
  78706. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78707. /***** Updraft *****/
  78708. var PhysicsUpdraftEvent = /** @class */ (function () {
  78709. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78710. this._scene = _scene;
  78711. this._origin = _origin;
  78712. this._radius = _radius;
  78713. this._strength = _strength;
  78714. this._height = _height;
  78715. this._updraftMode = _updraftMode;
  78716. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78717. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78718. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78719. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78720. this._physicsEngine = this._scene.getPhysicsEngine();
  78721. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78722. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78723. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78724. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78725. }
  78726. this._tickCallback = this._tick.bind(this);
  78727. }
  78728. /**
  78729. * Returns the data related to the updraft event (cylinder).
  78730. * @returns {PhysicsUpdraftEventData}
  78731. */
  78732. PhysicsUpdraftEvent.prototype.getData = function () {
  78733. this._dataFetched = true;
  78734. return {
  78735. cylinder: this._cylinder,
  78736. };
  78737. };
  78738. /**
  78739. * Enables the updraft.
  78740. */
  78741. PhysicsUpdraftEvent.prototype.enable = function () {
  78742. this._tickCallback.call(this);
  78743. this._scene.registerBeforeRender(this._tickCallback);
  78744. };
  78745. /**
  78746. * Disables the cortex.
  78747. */
  78748. PhysicsUpdraftEvent.prototype.disable = function () {
  78749. this._scene.unregisterBeforeRender(this._tickCallback);
  78750. };
  78751. /**
  78752. * Disposes the sphere.
  78753. * @param {bolean} force
  78754. */
  78755. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78756. var _this = this;
  78757. if (force === void 0) { force = true; }
  78758. if (force) {
  78759. this._cylinder.dispose();
  78760. }
  78761. else {
  78762. setTimeout(function () {
  78763. if (!_this._dataFetched) {
  78764. _this._cylinder.dispose();
  78765. }
  78766. }, 0);
  78767. }
  78768. };
  78769. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78770. if (impostor.mass === 0) {
  78771. return null;
  78772. }
  78773. if (!this._intersectsWithCylinder(impostor)) {
  78774. return null;
  78775. }
  78776. var impostorObjectCenter = impostor.getObjectCenter();
  78777. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78778. var direction = this._originDirection;
  78779. }
  78780. else {
  78781. var direction = impostorObjectCenter.subtract(this._originTop);
  78782. }
  78783. var multiplier = this._strength * -1;
  78784. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78785. return { force: force, contactPoint: impostorObjectCenter };
  78786. };
  78787. PhysicsUpdraftEvent.prototype._tick = function () {
  78788. var _this = this;
  78789. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78790. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78791. if (!impostorForceAndContactPoint) {
  78792. return;
  78793. }
  78794. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78795. });
  78796. };
  78797. /*** Helpers ***/
  78798. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78799. if (!this._cylinder) {
  78800. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78801. height: this._height,
  78802. diameter: this._radius * 2,
  78803. }, this._scene);
  78804. this._cylinder.isVisible = false;
  78805. }
  78806. };
  78807. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78808. var impostorObject = impostor.object;
  78809. this._prepareCylinder();
  78810. this._cylinder.position = this._cylinderPosition;
  78811. return this._cylinder.intersectsMesh(impostorObject, true);
  78812. };
  78813. return PhysicsUpdraftEvent;
  78814. }());
  78815. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78816. /***** Vortex *****/
  78817. var PhysicsVortexEvent = /** @class */ (function () {
  78818. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78819. this._scene = _scene;
  78820. this._origin = _origin;
  78821. this._radius = _radius;
  78822. this._strength = _strength;
  78823. this._height = _height;
  78824. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78825. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78826. this._updraftMultiplier = 0.02;
  78827. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78828. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78829. this._physicsEngine = this._scene.getPhysicsEngine();
  78830. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78831. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78832. this._tickCallback = this._tick.bind(this);
  78833. }
  78834. /**
  78835. * Returns the data related to the vortex event (cylinder).
  78836. * @returns {PhysicsVortexEventData}
  78837. */
  78838. PhysicsVortexEvent.prototype.getData = function () {
  78839. this._dataFetched = true;
  78840. return {
  78841. cylinder: this._cylinder,
  78842. };
  78843. };
  78844. /**
  78845. * Enables the vortex.
  78846. */
  78847. PhysicsVortexEvent.prototype.enable = function () {
  78848. this._tickCallback.call(this);
  78849. this._scene.registerBeforeRender(this._tickCallback);
  78850. };
  78851. /**
  78852. * Disables the cortex.
  78853. */
  78854. PhysicsVortexEvent.prototype.disable = function () {
  78855. this._scene.unregisterBeforeRender(this._tickCallback);
  78856. };
  78857. /**
  78858. * Disposes the sphere.
  78859. * @param {bolean} force
  78860. */
  78861. PhysicsVortexEvent.prototype.dispose = function (force) {
  78862. var _this = this;
  78863. if (force === void 0) { force = true; }
  78864. if (force) {
  78865. this._cylinder.dispose();
  78866. }
  78867. else {
  78868. setTimeout(function () {
  78869. if (!_this._dataFetched) {
  78870. _this._cylinder.dispose();
  78871. }
  78872. }, 0);
  78873. }
  78874. };
  78875. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78876. if (impostor.mass === 0) {
  78877. return null;
  78878. }
  78879. if (!this._intersectsWithCylinder(impostor)) {
  78880. return null;
  78881. }
  78882. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78883. return null;
  78884. }
  78885. var impostorObjectCenter = impostor.getObjectCenter();
  78886. 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)
  78887. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78888. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78889. var hit = ray.intersectsMesh(impostor.object);
  78890. var contactPoint = hit.pickedPoint;
  78891. if (!contactPoint) {
  78892. return null;
  78893. }
  78894. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78895. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78896. var directionToOrigin = contactPoint.normalize();
  78897. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78898. directionToOrigin = directionToOrigin.negate();
  78899. }
  78900. // TODO: find a more physically based solution
  78901. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78902. var forceX = directionToOrigin.x * this._strength / 8;
  78903. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78904. var forceZ = directionToOrigin.z * this._strength / 8;
  78905. }
  78906. else {
  78907. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78908. var forceY = this._originTop.y * this._updraftMultiplier;
  78909. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78910. }
  78911. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78912. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78913. return { force: force, contactPoint: impostorObjectCenter };
  78914. };
  78915. PhysicsVortexEvent.prototype._tick = function () {
  78916. var _this = this;
  78917. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78918. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78919. if (!impostorForceAndContactPoint) {
  78920. return;
  78921. }
  78922. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78923. });
  78924. };
  78925. /*** Helpers ***/
  78926. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78927. if (!this._cylinder) {
  78928. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78929. height: this._height,
  78930. diameter: this._radius * 2,
  78931. }, this._scene);
  78932. this._cylinder.isVisible = false;
  78933. }
  78934. };
  78935. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78936. var impostorObject = impostor.object;
  78937. this._prepareCylinder();
  78938. this._cylinder.position = this._cylinderPosition;
  78939. return this._cylinder.intersectsMesh(impostorObject, true);
  78940. };
  78941. return PhysicsVortexEvent;
  78942. }());
  78943. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78944. /***** Enums *****/
  78945. /**
  78946. * The strenght of the force in correspondence to the distance of the affected object
  78947. */
  78948. var PhysicsRadialImpulseFalloff;
  78949. (function (PhysicsRadialImpulseFalloff) {
  78950. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78951. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78952. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78953. /**
  78954. * The strenght of the force in correspondence to the distance of the affected object
  78955. */
  78956. var PhysicsUpdraftMode;
  78957. (function (PhysicsUpdraftMode) {
  78958. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78959. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78960. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78961. })(BABYLON || (BABYLON = {}));
  78962. //# sourceMappingURL=babylon.physicsHelper.js.map
  78963. "use strict";
  78964. var BABYLON;
  78965. (function (BABYLON) {
  78966. var CannonJSPlugin = /** @class */ (function () {
  78967. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78968. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78969. if (iterations === void 0) { iterations = 10; }
  78970. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78971. this.name = "CannonJSPlugin";
  78972. this._physicsMaterials = new Array();
  78973. this._fixedTimeStep = 1 / 60;
  78974. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78975. this.BJSCANNON = CANNON;
  78976. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78977. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78978. this._tmpPosition = BABYLON.Vector3.Zero();
  78979. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78980. this._tmpUnityRotation = new BABYLON.Quaternion();
  78981. if (!this.isSupported()) {
  78982. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78983. return;
  78984. }
  78985. this._extendNamespace();
  78986. this.world = new this.BJSCANNON.World();
  78987. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78988. this.world.solver.iterations = iterations;
  78989. }
  78990. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78991. this.world.gravity.copy(gravity);
  78992. };
  78993. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78994. this._fixedTimeStep = timeStep;
  78995. };
  78996. CannonJSPlugin.prototype.getTimeStep = function () {
  78997. return this._fixedTimeStep;
  78998. };
  78999. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  79000. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  79001. };
  79002. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79003. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  79004. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  79005. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  79006. };
  79007. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79008. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  79009. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  79010. impostor.physicsBody.applyForce(impulse, worldPoint);
  79011. };
  79012. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79013. //parent-child relationship. Does this impostor has a parent impostor?
  79014. if (impostor.parent) {
  79015. if (impostor.physicsBody) {
  79016. this.removePhysicsBody(impostor);
  79017. //TODO is that needed?
  79018. impostor.forceUpdate();
  79019. }
  79020. return;
  79021. }
  79022. //should a new body be created for this impostor?
  79023. if (impostor.isBodyInitRequired()) {
  79024. var shape = this._createShape(impostor);
  79025. //unregister events, if body is being changed
  79026. var oldBody = impostor.physicsBody;
  79027. if (oldBody) {
  79028. this.removePhysicsBody(impostor);
  79029. }
  79030. //create the body and material
  79031. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  79032. var bodyCreationObject = {
  79033. mass: impostor.getParam("mass"),
  79034. material: material
  79035. };
  79036. // A simple extend, in case native options were used.
  79037. var nativeOptions = impostor.getParam("nativeOptions");
  79038. for (var key in nativeOptions) {
  79039. if (nativeOptions.hasOwnProperty(key)) {
  79040. bodyCreationObject[key] = nativeOptions[key];
  79041. }
  79042. }
  79043. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  79044. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  79045. this.world.addEventListener("preStep", impostor.beforeStep);
  79046. this.world.addEventListener("postStep", impostor.afterStep);
  79047. impostor.physicsBody.addShape(shape);
  79048. this.world.add(impostor.physicsBody);
  79049. //try to keep the body moving in the right direction by taking old properties.
  79050. //Should be tested!
  79051. if (oldBody) {
  79052. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  79053. impostor.physicsBody[param].copy(oldBody[param]);
  79054. });
  79055. }
  79056. this._processChildMeshes(impostor);
  79057. }
  79058. //now update the body's transformation
  79059. this._updatePhysicsBodyTransformation(impostor);
  79060. };
  79061. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  79062. var _this = this;
  79063. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  79064. var currentRotation = mainImpostor.object.rotationQuaternion;
  79065. if (meshChildren.length) {
  79066. var processMesh = function (localPosition, mesh) {
  79067. if (!currentRotation || !mesh.rotationQuaternion) {
  79068. return;
  79069. }
  79070. var childImpostor = mesh.getPhysicsImpostor();
  79071. if (childImpostor) {
  79072. var parent = childImpostor.parent;
  79073. if (parent !== mainImpostor) {
  79074. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  79075. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  79076. if (childImpostor.physicsBody) {
  79077. _this.removePhysicsBody(childImpostor);
  79078. childImpostor.physicsBody = null;
  79079. }
  79080. childImpostor.parent = mainImpostor;
  79081. childImpostor.resetUpdateFlags();
  79082. 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));
  79083. //Add the mass of the children.
  79084. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  79085. }
  79086. }
  79087. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  79088. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  79089. };
  79090. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  79091. }
  79092. };
  79093. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79094. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  79095. this.world.removeEventListener("preStep", impostor.beforeStep);
  79096. this.world.removeEventListener("postStep", impostor.afterStep);
  79097. this.world.remove(impostor.physicsBody);
  79098. };
  79099. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79100. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79101. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79102. if (!mainBody || !connectedBody) {
  79103. return;
  79104. }
  79105. var constraint;
  79106. var jointData = impostorJoint.joint.jointData;
  79107. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  79108. var constraintData = {
  79109. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  79110. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  79111. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  79112. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  79113. maxForce: jointData.nativeParams.maxForce,
  79114. collideConnected: !!jointData.collision
  79115. };
  79116. switch (impostorJoint.joint.type) {
  79117. case BABYLON.PhysicsJoint.HingeJoint:
  79118. case BABYLON.PhysicsJoint.Hinge2Joint:
  79119. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  79120. break;
  79121. case BABYLON.PhysicsJoint.DistanceJoint:
  79122. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  79123. break;
  79124. case BABYLON.PhysicsJoint.SpringJoint:
  79125. var springData = jointData;
  79126. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  79127. restLength: springData.length,
  79128. stiffness: springData.stiffness,
  79129. damping: springData.damping,
  79130. localAnchorA: constraintData.pivotA,
  79131. localAnchorB: constraintData.pivotB
  79132. });
  79133. break;
  79134. case BABYLON.PhysicsJoint.LockJoint:
  79135. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  79136. break;
  79137. case BABYLON.PhysicsJoint.PointToPointJoint:
  79138. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79139. default:
  79140. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  79141. break;
  79142. }
  79143. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  79144. constraint.collideConnected = !!jointData.collision;
  79145. impostorJoint.joint.physicsJoint = constraint;
  79146. //don't add spring as constraint, as it is not one.
  79147. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  79148. this.world.addConstraint(constraint);
  79149. }
  79150. else {
  79151. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  79152. constraint.applyForce();
  79153. });
  79154. }
  79155. };
  79156. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79157. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  79158. };
  79159. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  79160. var index;
  79161. var mat;
  79162. for (index = 0; index < this._physicsMaterials.length; index++) {
  79163. mat = this._physicsMaterials[index];
  79164. if (mat.friction === friction && mat.restitution === restitution) {
  79165. return mat;
  79166. }
  79167. }
  79168. var currentMat = new this.BJSCANNON.Material(name);
  79169. currentMat.friction = friction;
  79170. currentMat.restitution = restitution;
  79171. this._physicsMaterials.push(currentMat);
  79172. return currentMat;
  79173. };
  79174. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  79175. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  79176. };
  79177. CannonJSPlugin.prototype._createShape = function (impostor) {
  79178. var object = impostor.object;
  79179. var returnValue;
  79180. var extendSize = impostor.getObjectExtendSize();
  79181. switch (impostor.type) {
  79182. case BABYLON.PhysicsImpostor.SphereImpostor:
  79183. var radiusX = extendSize.x;
  79184. var radiusY = extendSize.y;
  79185. var radiusZ = extendSize.z;
  79186. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  79187. break;
  79188. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  79189. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79190. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  79191. break;
  79192. case BABYLON.PhysicsImpostor.BoxImpostor:
  79193. var box = extendSize.scale(0.5);
  79194. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  79195. break;
  79196. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79197. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  79198. returnValue = new this.BJSCANNON.Plane();
  79199. break;
  79200. case BABYLON.PhysicsImpostor.MeshImpostor:
  79201. // should transform the vertex data to world coordinates!!
  79202. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  79203. var rawFaces = object.getIndices ? object.getIndices() : [];
  79204. if (!rawVerts)
  79205. return;
  79206. // get only scale! so the object could transform correctly.
  79207. var oldPosition = object.position.clone();
  79208. var oldRotation = object.rotation && object.rotation.clone();
  79209. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  79210. object.position.copyFromFloats(0, 0, 0);
  79211. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79212. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79213. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79214. var transform = object.computeWorldMatrix(true);
  79215. // convert rawVerts to object space
  79216. var temp = new Array();
  79217. var index;
  79218. for (index = 0; index < rawVerts.length; index += 3) {
  79219. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  79220. }
  79221. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  79222. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  79223. //now set back the transformation!
  79224. object.position.copyFrom(oldPosition);
  79225. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  79226. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  79227. break;
  79228. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  79229. var oldPosition2 = object.position.clone();
  79230. var oldRotation2 = object.rotation && object.rotation.clone();
  79231. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  79232. object.position.copyFromFloats(0, 0, 0);
  79233. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79234. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79235. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79236. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  79237. returnValue = this._createHeightmap(object);
  79238. object.position.copyFrom(oldPosition2);
  79239. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  79240. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  79241. object.computeWorldMatrix(true);
  79242. break;
  79243. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79244. returnValue = new this.BJSCANNON.Particle();
  79245. break;
  79246. }
  79247. return returnValue;
  79248. };
  79249. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  79250. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79251. var transform = object.computeWorldMatrix(true);
  79252. // convert rawVerts to object space
  79253. var temp = new Array();
  79254. var index;
  79255. for (index = 0; index < pos.length; index += 3) {
  79256. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  79257. }
  79258. pos = temp;
  79259. var matrix = new Array();
  79260. //For now pointDepth will not be used and will be automatically calculated.
  79261. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  79262. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  79263. var boundingInfo = object.getBoundingInfo();
  79264. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  79265. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  79266. var elementSize = dim * 2 / arraySize;
  79267. for (var i = 0; i < pos.length; i = i + 3) {
  79268. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  79269. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  79270. var y = -pos[i + 2] + minY;
  79271. if (!matrix[x]) {
  79272. matrix[x] = [];
  79273. }
  79274. if (!matrix[x][z]) {
  79275. matrix[x][z] = y;
  79276. }
  79277. matrix[x][z] = Math.max(y, matrix[x][z]);
  79278. }
  79279. for (var x = 0; x <= arraySize; ++x) {
  79280. if (!matrix[x]) {
  79281. var loc = 1;
  79282. while (!matrix[(x + loc) % arraySize]) {
  79283. loc++;
  79284. }
  79285. matrix[x] = matrix[(x + loc) % arraySize].slice();
  79286. //console.log("missing x", x);
  79287. }
  79288. for (var z = 0; z <= arraySize; ++z) {
  79289. if (!matrix[x][z]) {
  79290. var loc = 1;
  79291. var newValue;
  79292. while (newValue === undefined) {
  79293. newValue = matrix[x][(z + loc++) % arraySize];
  79294. }
  79295. matrix[x][z] = newValue;
  79296. }
  79297. }
  79298. }
  79299. var shape = new this.BJSCANNON.Heightfield(matrix, {
  79300. elementSize: elementSize
  79301. });
  79302. //For future reference, needed for body transformation
  79303. shape.minY = minY;
  79304. return shape;
  79305. };
  79306. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  79307. var object = impostor.object;
  79308. //make sure it is updated...
  79309. object.computeWorldMatrix && object.computeWorldMatrix(true);
  79310. // The delta between the mesh position and the mesh bounding box center
  79311. var bInfo = object.getBoundingInfo();
  79312. if (!bInfo)
  79313. return;
  79314. var center = impostor.getObjectCenter();
  79315. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  79316. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  79317. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  79318. this._tmpPosition.copyFrom(center);
  79319. var quaternion = object.rotationQuaternion;
  79320. if (!quaternion) {
  79321. return;
  79322. }
  79323. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  79324. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  79325. //-90 DEG in X, precalculated
  79326. quaternion = quaternion.multiply(this._minus90X);
  79327. //Invert! (Precalculated, 90 deg in X)
  79328. //No need to clone. this will never change.
  79329. impostor.setDeltaRotation(this._plus90X);
  79330. }
  79331. //If it is a heightfield, if should be centered.
  79332. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  79333. var mesh = object;
  79334. var boundingInfo = mesh.getBoundingInfo();
  79335. //calculate the correct body position:
  79336. var rotationQuaternion = mesh.rotationQuaternion;
  79337. mesh.rotationQuaternion = this._tmpUnityRotation;
  79338. mesh.computeWorldMatrix(true);
  79339. //get original center with no rotation
  79340. var c = center.clone();
  79341. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  79342. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  79343. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  79344. mesh.setPreTransformMatrix(p);
  79345. mesh.computeWorldMatrix(true);
  79346. //calculate the translation
  79347. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79348. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79349. //add it inverted to the delta
  79350. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79351. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79352. //rotation is back
  79353. mesh.rotationQuaternion = rotationQuaternion;
  79354. mesh.setPreTransformMatrix(oldPivot);
  79355. mesh.computeWorldMatrix(true);
  79356. }
  79357. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79358. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79359. //this._tmpPosition.copyFrom(object.position);
  79360. }
  79361. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79362. //Now update the impostor object
  79363. impostor.physicsBody.position.copy(this._tmpPosition);
  79364. impostor.physicsBody.quaternion.copy(quaternion);
  79365. };
  79366. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79367. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79368. if (impostor.object.rotationQuaternion) {
  79369. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79370. }
  79371. };
  79372. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79373. impostor.physicsBody.position.copy(newPosition);
  79374. impostor.physicsBody.quaternion.copy(newRotation);
  79375. };
  79376. CannonJSPlugin.prototype.isSupported = function () {
  79377. return this.BJSCANNON !== undefined;
  79378. };
  79379. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79380. impostor.physicsBody.velocity.copy(velocity);
  79381. };
  79382. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79383. impostor.physicsBody.angularVelocity.copy(velocity);
  79384. };
  79385. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79386. var v = impostor.physicsBody.velocity;
  79387. if (!v) {
  79388. return null;
  79389. }
  79390. return new BABYLON.Vector3(v.x, v.y, v.z);
  79391. };
  79392. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79393. var v = impostor.physicsBody.angularVelocity;
  79394. if (!v) {
  79395. return null;
  79396. }
  79397. return new BABYLON.Vector3(v.x, v.y, v.z);
  79398. };
  79399. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79400. impostor.physicsBody.mass = mass;
  79401. impostor.physicsBody.updateMassProperties();
  79402. };
  79403. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79404. return impostor.physicsBody.mass;
  79405. };
  79406. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79407. return impostor.physicsBody.material.friction;
  79408. };
  79409. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79410. impostor.physicsBody.material.friction = friction;
  79411. };
  79412. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79413. return impostor.physicsBody.material.restitution;
  79414. };
  79415. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79416. impostor.physicsBody.material.restitution = restitution;
  79417. };
  79418. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79419. impostor.physicsBody.sleep();
  79420. };
  79421. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79422. impostor.physicsBody.wakeUp();
  79423. };
  79424. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79425. joint.physicsJoint.distance = maxDistance;
  79426. };
  79427. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79428. // if (!motorIndex) {
  79429. // joint.physicsJoint.enableMotor();
  79430. // }
  79431. // }
  79432. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79433. // if (!motorIndex) {
  79434. // joint.physicsJoint.disableMotor();
  79435. // }
  79436. // }
  79437. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79438. if (!motorIndex) {
  79439. joint.physicsJoint.enableMotor();
  79440. joint.physicsJoint.setMotorSpeed(speed);
  79441. if (maxForce) {
  79442. this.setLimit(joint, maxForce);
  79443. }
  79444. }
  79445. };
  79446. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79447. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79448. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79449. };
  79450. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79451. var body = impostor.physicsBody;
  79452. mesh.position.x = body.position.x;
  79453. mesh.position.y = body.position.y;
  79454. mesh.position.z = body.position.z;
  79455. if (mesh.rotationQuaternion) {
  79456. mesh.rotationQuaternion.x = body.quaternion.x;
  79457. mesh.rotationQuaternion.y = body.quaternion.y;
  79458. mesh.rotationQuaternion.z = body.quaternion.z;
  79459. mesh.rotationQuaternion.w = body.quaternion.w;
  79460. }
  79461. };
  79462. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79463. var shape = impostor.physicsBody.shapes[0];
  79464. return shape.boundingSphereRadius;
  79465. };
  79466. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79467. var shape = impostor.physicsBody.shapes[0];
  79468. result.x = shape.halfExtents.x * 2;
  79469. result.y = shape.halfExtents.y * 2;
  79470. result.z = shape.halfExtents.z * 2;
  79471. };
  79472. CannonJSPlugin.prototype.dispose = function () {
  79473. };
  79474. CannonJSPlugin.prototype._extendNamespace = function () {
  79475. //this will force cannon to execute at least one step when using interpolation
  79476. var step_tmp1 = new this.BJSCANNON.Vec3();
  79477. var Engine = this.BJSCANNON;
  79478. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79479. maxSubSteps = maxSubSteps || 10;
  79480. timeSinceLastCalled = timeSinceLastCalled || 0;
  79481. if (timeSinceLastCalled === 0) {
  79482. this.internalStep(dt);
  79483. this.time += dt;
  79484. }
  79485. else {
  79486. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79487. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79488. var t0 = performance.now();
  79489. for (var i = 0; i !== internalSteps; i++) {
  79490. this.internalStep(dt);
  79491. if (performance.now() - t0 > dt * 1000) {
  79492. break;
  79493. }
  79494. }
  79495. this.time += timeSinceLastCalled;
  79496. var h = this.time % dt;
  79497. var h_div_dt = h / dt;
  79498. var interpvelo = step_tmp1;
  79499. var bodies = this.bodies;
  79500. for (var j = 0; j !== bodies.length; j++) {
  79501. var b = bodies[j];
  79502. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79503. b.position.vsub(b.previousPosition, interpvelo);
  79504. interpvelo.scale(h_div_dt, interpvelo);
  79505. b.position.vadd(interpvelo, b.interpolatedPosition);
  79506. }
  79507. else {
  79508. b.interpolatedPosition.copy(b.position);
  79509. b.interpolatedQuaternion.copy(b.quaternion);
  79510. }
  79511. }
  79512. }
  79513. };
  79514. };
  79515. return CannonJSPlugin;
  79516. }());
  79517. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79518. })(BABYLON || (BABYLON = {}));
  79519. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79520. "use strict";
  79521. var BABYLON;
  79522. (function (BABYLON) {
  79523. var OimoJSPlugin = /** @class */ (function () {
  79524. function OimoJSPlugin(iterations) {
  79525. this.name = "OimoJSPlugin";
  79526. this._tmpImpostorsArray = [];
  79527. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79528. this.BJSOIMO = OIMO;
  79529. this.world = new this.BJSOIMO.World({
  79530. iterations: iterations
  79531. });
  79532. this.world.clear();
  79533. }
  79534. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79535. this.world.gravity.copy(gravity);
  79536. };
  79537. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79538. this.world.timeStep = timeStep;
  79539. };
  79540. OimoJSPlugin.prototype.getTimeStep = function () {
  79541. return this.world.timeStep;
  79542. };
  79543. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79544. var _this = this;
  79545. impostors.forEach(function (impostor) {
  79546. impostor.beforeStep();
  79547. });
  79548. this.world.step();
  79549. impostors.forEach(function (impostor) {
  79550. impostor.afterStep();
  79551. //update the ordered impostors array
  79552. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79553. });
  79554. //check for collisions
  79555. var contact = this.world.contacts;
  79556. while (contact !== null) {
  79557. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79558. contact = contact.next;
  79559. continue;
  79560. }
  79561. //is this body colliding with any other? get the impostor
  79562. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79563. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79564. if (!mainImpostor || !collidingImpostor) {
  79565. contact = contact.next;
  79566. continue;
  79567. }
  79568. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79569. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79570. contact = contact.next;
  79571. }
  79572. };
  79573. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79574. var mass = impostor.physicsBody.mass;
  79575. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79576. };
  79577. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79578. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79579. this.applyImpulse(impostor, force, contactPoint);
  79580. };
  79581. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79582. var _this = this;
  79583. //parent-child relationship. Does this impostor has a parent impostor?
  79584. if (impostor.parent) {
  79585. if (impostor.physicsBody) {
  79586. this.removePhysicsBody(impostor);
  79587. //TODO is that needed?
  79588. impostor.forceUpdate();
  79589. }
  79590. return;
  79591. }
  79592. if (impostor.isBodyInitRequired()) {
  79593. var bodyConfig = {
  79594. name: impostor.uniqueId,
  79595. //Oimo must have mass, also for static objects.
  79596. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79597. size: [],
  79598. type: [],
  79599. pos: [],
  79600. posShape: [],
  79601. rot: [],
  79602. rotShape: [],
  79603. move: impostor.getParam("mass") !== 0,
  79604. density: impostor.getParam("mass"),
  79605. friction: impostor.getParam("friction"),
  79606. restitution: impostor.getParam("restitution"),
  79607. //Supporting older versions of Oimo
  79608. world: this.world
  79609. };
  79610. var impostors = [impostor];
  79611. var addToArray = function (parent) {
  79612. if (!parent.getChildMeshes)
  79613. return;
  79614. parent.getChildMeshes().forEach(function (m) {
  79615. if (m.physicsImpostor) {
  79616. impostors.push(m.physicsImpostor);
  79617. //m.physicsImpostor._init();
  79618. }
  79619. });
  79620. };
  79621. addToArray(impostor.object);
  79622. var checkWithEpsilon_1 = function (value) {
  79623. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79624. };
  79625. impostors.forEach(function (i) {
  79626. if (!i.object.rotationQuaternion) {
  79627. return;
  79628. }
  79629. //get the correct bounding box
  79630. var oldQuaternion = i.object.rotationQuaternion;
  79631. var rot = oldQuaternion.toEulerAngles();
  79632. var extendSize = i.getObjectExtendSize();
  79633. var radToDeg = 57.295779513082320876;
  79634. if (i === impostor) {
  79635. var center = impostor.getObjectCenter();
  79636. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79637. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79638. //Can also use Array.prototype.push.apply
  79639. bodyConfig.pos.push(center.x);
  79640. bodyConfig.pos.push(center.y);
  79641. bodyConfig.pos.push(center.z);
  79642. bodyConfig.posShape.push(0, 0, 0);
  79643. //tmp solution
  79644. bodyConfig.rot.push(rot.x * radToDeg);
  79645. bodyConfig.rot.push(rot.y * radToDeg);
  79646. bodyConfig.rot.push(rot.z * radToDeg);
  79647. bodyConfig.rotShape.push(0, 0, 0);
  79648. }
  79649. else {
  79650. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79651. bodyConfig.posShape.push(localPosition.x);
  79652. bodyConfig.posShape.push(localPosition.y);
  79653. bodyConfig.posShape.push(localPosition.z);
  79654. bodyConfig.pos.push(0, 0, 0);
  79655. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79656. bodyConfig.rot.push(0);
  79657. bodyConfig.rot.push(0);
  79658. bodyConfig.rot.push(0);
  79659. bodyConfig.rotShape.push(rot.x * radToDeg);
  79660. bodyConfig.rotShape.push(rot.y * radToDeg);
  79661. bodyConfig.rotShape.push(rot.z * radToDeg);
  79662. }
  79663. // register mesh
  79664. switch (i.type) {
  79665. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79666. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79667. case BABYLON.PhysicsImpostor.SphereImpostor:
  79668. var radiusX = extendSize.x;
  79669. var radiusY = extendSize.y;
  79670. var radiusZ = extendSize.z;
  79671. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79672. bodyConfig.type.push('sphere');
  79673. //due to the way oimo works with compounds, add 3 times
  79674. bodyConfig.size.push(size);
  79675. bodyConfig.size.push(size);
  79676. bodyConfig.size.push(size);
  79677. break;
  79678. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79679. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79680. var sizeY = checkWithEpsilon_1(extendSize.y);
  79681. bodyConfig.type.push('cylinder');
  79682. bodyConfig.size.push(sizeX);
  79683. bodyConfig.size.push(sizeY);
  79684. //due to the way oimo works with compounds, add one more value.
  79685. bodyConfig.size.push(sizeY);
  79686. break;
  79687. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79688. case BABYLON.PhysicsImpostor.BoxImpostor:
  79689. default:
  79690. var sizeX = checkWithEpsilon_1(extendSize.x);
  79691. var sizeY = checkWithEpsilon_1(extendSize.y);
  79692. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79693. bodyConfig.type.push('box');
  79694. //if (i === impostor) {
  79695. bodyConfig.size.push(sizeX);
  79696. bodyConfig.size.push(sizeY);
  79697. bodyConfig.size.push(sizeZ);
  79698. //} else {
  79699. // bodyConfig.size.push(0,0,0);
  79700. //}
  79701. break;
  79702. }
  79703. //actually not needed, but hey...
  79704. i.object.rotationQuaternion = oldQuaternion;
  79705. });
  79706. impostor.physicsBody = this.world.add(bodyConfig);
  79707. }
  79708. else {
  79709. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79710. }
  79711. impostor.setDeltaPosition(this._tmpPositionVector);
  79712. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79713. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79714. };
  79715. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79716. //impostor.physicsBody.dispose();
  79717. //Same as : (older oimo versions)
  79718. this.world.removeRigidBody(impostor.physicsBody);
  79719. };
  79720. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79721. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79722. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79723. if (!mainBody || !connectedBody) {
  79724. return;
  79725. }
  79726. var jointData = impostorJoint.joint.jointData;
  79727. var options = jointData.nativeParams || {};
  79728. var type;
  79729. var nativeJointData = {
  79730. body1: mainBody,
  79731. body2: connectedBody,
  79732. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79733. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79734. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79735. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79736. min: options.min,
  79737. max: options.max,
  79738. collision: options.collision || jointData.collision,
  79739. spring: options.spring,
  79740. //supporting older version of Oimo
  79741. world: this.world
  79742. };
  79743. switch (impostorJoint.joint.type) {
  79744. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79745. type = "jointBall";
  79746. break;
  79747. case BABYLON.PhysicsJoint.SpringJoint:
  79748. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79749. var springData = jointData;
  79750. nativeJointData.min = springData.length || nativeJointData.min;
  79751. //Max should also be set, just make sure it is at least min
  79752. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79753. case BABYLON.PhysicsJoint.DistanceJoint:
  79754. type = "jointDistance";
  79755. nativeJointData.max = jointData.maxDistance;
  79756. break;
  79757. case BABYLON.PhysicsJoint.PrismaticJoint:
  79758. type = "jointPrisme";
  79759. break;
  79760. case BABYLON.PhysicsJoint.SliderJoint:
  79761. type = "jointSlide";
  79762. break;
  79763. case BABYLON.PhysicsJoint.WheelJoint:
  79764. type = "jointWheel";
  79765. break;
  79766. case BABYLON.PhysicsJoint.HingeJoint:
  79767. default:
  79768. type = "jointHinge";
  79769. break;
  79770. }
  79771. nativeJointData.type = type;
  79772. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79773. };
  79774. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79775. //Bug in Oimo prevents us from disposing a joint in the playground
  79776. //joint.joint.physicsJoint.dispose();
  79777. //So we will bruteforce it!
  79778. try {
  79779. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79780. }
  79781. catch (e) {
  79782. BABYLON.Tools.Warn(e);
  79783. }
  79784. };
  79785. OimoJSPlugin.prototype.isSupported = function () {
  79786. return this.BJSOIMO !== undefined;
  79787. };
  79788. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79789. if (!impostor.physicsBody.sleeping) {
  79790. //TODO check that
  79791. /*if (impostor.physicsBody.shapes.next) {
  79792. var parentShape = this._getLastShape(impostor.physicsBody);
  79793. impostor.object.position.copyFrom(parentShape.position);
  79794. console.log(parentShape.position);
  79795. } else {*/
  79796. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79797. //}
  79798. if (impostor.object.rotationQuaternion) {
  79799. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79800. }
  79801. }
  79802. };
  79803. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79804. var body = impostor.physicsBody;
  79805. body.position.copy(newPosition);
  79806. body.orientation.copy(newRotation);
  79807. body.syncShapes();
  79808. body.awake();
  79809. };
  79810. /*private _getLastShape(body: any): any {
  79811. var lastShape = body.shapes;
  79812. while (lastShape.next) {
  79813. lastShape = lastShape.next;
  79814. }
  79815. return lastShape;
  79816. }*/
  79817. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79818. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79819. };
  79820. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79821. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79822. };
  79823. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79824. var v = impostor.physicsBody.linearVelocity;
  79825. if (!v) {
  79826. return null;
  79827. }
  79828. return new BABYLON.Vector3(v.x, v.y, v.z);
  79829. };
  79830. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79831. var v = impostor.physicsBody.angularVelocity;
  79832. if (!v) {
  79833. return null;
  79834. }
  79835. return new BABYLON.Vector3(v.x, v.y, v.z);
  79836. };
  79837. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79838. var staticBody = mass === 0;
  79839. //this will actually set the body's density and not its mass.
  79840. //But this is how oimo treats the mass variable.
  79841. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79842. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79843. };
  79844. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79845. return impostor.physicsBody.shapes.density;
  79846. };
  79847. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79848. return impostor.physicsBody.shapes.friction;
  79849. };
  79850. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79851. impostor.physicsBody.shapes.friction = friction;
  79852. };
  79853. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79854. return impostor.physicsBody.shapes.restitution;
  79855. };
  79856. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79857. impostor.physicsBody.shapes.restitution = restitution;
  79858. };
  79859. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79860. impostor.physicsBody.sleep();
  79861. };
  79862. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79863. impostor.physicsBody.awake();
  79864. };
  79865. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79866. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79867. if (minDistance !== void 0) {
  79868. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79869. }
  79870. };
  79871. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79872. //TODO separate rotational and transational motors.
  79873. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79874. if (motor) {
  79875. motor.setMotor(speed, maxForce);
  79876. }
  79877. };
  79878. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79879. //TODO separate rotational and transational motors.
  79880. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79881. if (motor) {
  79882. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79883. }
  79884. };
  79885. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79886. var body = impostor.physicsBody;
  79887. mesh.position.x = body.position.x;
  79888. mesh.position.y = body.position.y;
  79889. mesh.position.z = body.position.z;
  79890. if (mesh.rotationQuaternion) {
  79891. mesh.rotationQuaternion.x = body.orientation.x;
  79892. mesh.rotationQuaternion.y = body.orientation.y;
  79893. mesh.rotationQuaternion.z = body.orientation.z;
  79894. mesh.rotationQuaternion.w = body.orientation.s;
  79895. }
  79896. };
  79897. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79898. return impostor.physicsBody.shapes.radius;
  79899. };
  79900. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79901. var shape = impostor.physicsBody.shapes;
  79902. result.x = shape.halfWidth * 2;
  79903. result.y = shape.halfHeight * 2;
  79904. result.z = shape.halfDepth * 2;
  79905. };
  79906. OimoJSPlugin.prototype.dispose = function () {
  79907. this.world.clear();
  79908. };
  79909. return OimoJSPlugin;
  79910. }());
  79911. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79912. })(BABYLON || (BABYLON = {}));
  79913. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79914. "use strict";
  79915. var BABYLON;
  79916. (function (BABYLON) {
  79917. /*
  79918. * Based on jsTGALoader - Javascript loader for TGA file
  79919. * By Vincent Thibault
  79920. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79921. */
  79922. var TGATools = /** @class */ (function () {
  79923. function TGATools() {
  79924. }
  79925. TGATools.GetTGAHeader = function (data) {
  79926. var offset = 0;
  79927. var header = {
  79928. id_length: data[offset++],
  79929. colormap_type: data[offset++],
  79930. image_type: data[offset++],
  79931. colormap_index: data[offset++] | data[offset++] << 8,
  79932. colormap_length: data[offset++] | data[offset++] << 8,
  79933. colormap_size: data[offset++],
  79934. origin: [
  79935. data[offset++] | data[offset++] << 8,
  79936. data[offset++] | data[offset++] << 8
  79937. ],
  79938. width: data[offset++] | data[offset++] << 8,
  79939. height: data[offset++] | data[offset++] << 8,
  79940. pixel_size: data[offset++],
  79941. flags: data[offset++]
  79942. };
  79943. return header;
  79944. };
  79945. TGATools.UploadContent = function (gl, data) {
  79946. // Not enough data to contain header ?
  79947. if (data.length < 19) {
  79948. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79949. return;
  79950. }
  79951. // Read Header
  79952. var offset = 18;
  79953. var header = TGATools.GetTGAHeader(data);
  79954. // Assume it's a valid Targa file.
  79955. if (header.id_length + offset > data.length) {
  79956. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79957. return;
  79958. }
  79959. // Skip not needed data
  79960. offset += header.id_length;
  79961. var use_rle = false;
  79962. var use_pal = false;
  79963. var use_grey = false;
  79964. // Get some informations.
  79965. switch (header.image_type) {
  79966. case TGATools._TYPE_RLE_INDEXED:
  79967. use_rle = true;
  79968. case TGATools._TYPE_INDEXED:
  79969. use_pal = true;
  79970. break;
  79971. case TGATools._TYPE_RLE_RGB:
  79972. use_rle = true;
  79973. case TGATools._TYPE_RGB:
  79974. // use_rgb = true;
  79975. break;
  79976. case TGATools._TYPE_RLE_GREY:
  79977. use_rle = true;
  79978. case TGATools._TYPE_GREY:
  79979. use_grey = true;
  79980. break;
  79981. }
  79982. var pixel_data;
  79983. // var numAlphaBits = header.flags & 0xf;
  79984. var pixel_size = header.pixel_size >> 3;
  79985. var pixel_total = header.width * header.height * pixel_size;
  79986. // Read palettes
  79987. var palettes;
  79988. if (use_pal) {
  79989. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79990. }
  79991. // Read LRE
  79992. if (use_rle) {
  79993. pixel_data = new Uint8Array(pixel_total);
  79994. var c, count, i;
  79995. var localOffset = 0;
  79996. var pixels = new Uint8Array(pixel_size);
  79997. while (offset < pixel_total && localOffset < pixel_total) {
  79998. c = data[offset++];
  79999. count = (c & 0x7f) + 1;
  80000. // RLE pixels
  80001. if (c & 0x80) {
  80002. // Bind pixel tmp array
  80003. for (i = 0; i < pixel_size; ++i) {
  80004. pixels[i] = data[offset++];
  80005. }
  80006. // Copy pixel array
  80007. for (i = 0; i < count; ++i) {
  80008. pixel_data.set(pixels, localOffset + i * pixel_size);
  80009. }
  80010. localOffset += pixel_size * count;
  80011. }
  80012. else {
  80013. count *= pixel_size;
  80014. for (i = 0; i < count; ++i) {
  80015. pixel_data[localOffset + i] = data[offset++];
  80016. }
  80017. localOffset += count;
  80018. }
  80019. }
  80020. }
  80021. else {
  80022. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  80023. }
  80024. // Load to texture
  80025. var x_start, y_start, x_step, y_step, y_end, x_end;
  80026. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  80027. default:
  80028. case TGATools._ORIGIN_UL:
  80029. x_start = 0;
  80030. x_step = 1;
  80031. x_end = header.width;
  80032. y_start = 0;
  80033. y_step = 1;
  80034. y_end = header.height;
  80035. break;
  80036. case TGATools._ORIGIN_BL:
  80037. x_start = 0;
  80038. x_step = 1;
  80039. x_end = header.width;
  80040. y_start = header.height - 1;
  80041. y_step = -1;
  80042. y_end = -1;
  80043. break;
  80044. case TGATools._ORIGIN_UR:
  80045. x_start = header.width - 1;
  80046. x_step = -1;
  80047. x_end = -1;
  80048. y_start = 0;
  80049. y_step = 1;
  80050. y_end = header.height;
  80051. break;
  80052. case TGATools._ORIGIN_BR:
  80053. x_start = header.width - 1;
  80054. x_step = -1;
  80055. x_end = -1;
  80056. y_start = header.height - 1;
  80057. y_step = -1;
  80058. y_end = -1;
  80059. break;
  80060. }
  80061. // Load the specify method
  80062. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  80063. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  80064. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  80065. };
  80066. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80067. var image = pixel_data, colormap = palettes;
  80068. var width = header.width, height = header.height;
  80069. var color, i = 0, x, y;
  80070. var imageData = new Uint8Array(width * height * 4);
  80071. for (y = y_start; y !== y_end; y += y_step) {
  80072. for (x = x_start; x !== x_end; x += x_step, i++) {
  80073. color = image[i];
  80074. imageData[(x + width * y) * 4 + 3] = 255;
  80075. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  80076. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  80077. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  80078. }
  80079. }
  80080. return imageData;
  80081. };
  80082. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80083. var image = pixel_data;
  80084. var width = header.width, height = header.height;
  80085. var color, i = 0, x, y;
  80086. var imageData = new Uint8Array(width * height * 4);
  80087. for (y = y_start; y !== y_end; y += y_step) {
  80088. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  80089. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  80090. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  80091. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  80092. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  80093. imageData[(x + width * y) * 4 + 0] = r;
  80094. imageData[(x + width * y) * 4 + 1] = g;
  80095. imageData[(x + width * y) * 4 + 2] = b;
  80096. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  80097. }
  80098. }
  80099. return imageData;
  80100. };
  80101. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80102. var image = pixel_data;
  80103. var width = header.width, height = header.height;
  80104. var i = 0, x, y;
  80105. var imageData = new Uint8Array(width * height * 4);
  80106. for (y = y_start; y !== y_end; y += y_step) {
  80107. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  80108. imageData[(x + width * y) * 4 + 3] = 255;
  80109. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80110. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  80111. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  80112. }
  80113. }
  80114. return imageData;
  80115. };
  80116. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80117. var image = pixel_data;
  80118. var width = header.width, height = header.height;
  80119. var i = 0, x, y;
  80120. var imageData = new Uint8Array(width * height * 4);
  80121. for (y = y_start; y !== y_end; y += y_step) {
  80122. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  80123. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80124. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  80125. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  80126. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  80127. }
  80128. }
  80129. return imageData;
  80130. };
  80131. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80132. var image = pixel_data;
  80133. var width = header.width, height = header.height;
  80134. var color, i = 0, x, y;
  80135. var imageData = new Uint8Array(width * height * 4);
  80136. for (y = y_start; y !== y_end; y += y_step) {
  80137. for (x = x_start; x !== x_end; x += x_step, i++) {
  80138. color = image[i];
  80139. imageData[(x + width * y) * 4 + 0] = color;
  80140. imageData[(x + width * y) * 4 + 1] = color;
  80141. imageData[(x + width * y) * 4 + 2] = color;
  80142. imageData[(x + width * y) * 4 + 3] = 255;
  80143. }
  80144. }
  80145. return imageData;
  80146. };
  80147. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  80148. var image = pixel_data;
  80149. var width = header.width, height = header.height;
  80150. var i = 0, x, y;
  80151. var imageData = new Uint8Array(width * height * 4);
  80152. for (y = y_start; y !== y_end; y += y_step) {
  80153. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  80154. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  80155. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  80156. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  80157. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  80158. }
  80159. }
  80160. return imageData;
  80161. };
  80162. //private static _TYPE_NO_DATA = 0;
  80163. TGATools._TYPE_INDEXED = 1;
  80164. TGATools._TYPE_RGB = 2;
  80165. TGATools._TYPE_GREY = 3;
  80166. TGATools._TYPE_RLE_INDEXED = 9;
  80167. TGATools._TYPE_RLE_RGB = 10;
  80168. TGATools._TYPE_RLE_GREY = 11;
  80169. TGATools._ORIGIN_MASK = 0x30;
  80170. TGATools._ORIGIN_SHIFT = 0x04;
  80171. TGATools._ORIGIN_BL = 0x00;
  80172. TGATools._ORIGIN_BR = 0x01;
  80173. TGATools._ORIGIN_UL = 0x02;
  80174. TGATools._ORIGIN_UR = 0x03;
  80175. return TGATools;
  80176. }());
  80177. BABYLON.TGATools = TGATools;
  80178. })(BABYLON || (BABYLON = {}));
  80179. //# sourceMappingURL=babylon.tga.js.map
  80180. "use strict";
  80181. var BABYLON;
  80182. (function (BABYLON) {
  80183. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  80184. // All values and structures referenced from:
  80185. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  80186. var DDS_MAGIC = 0x20534444;
  80187. var
  80188. //DDSD_CAPS = 0x1,
  80189. //DDSD_HEIGHT = 0x2,
  80190. //DDSD_WIDTH = 0x4,
  80191. //DDSD_PITCH = 0x8,
  80192. //DDSD_PIXELFORMAT = 0x1000,
  80193. DDSD_MIPMAPCOUNT = 0x20000;
  80194. //DDSD_LINEARSIZE = 0x80000,
  80195. //DDSD_DEPTH = 0x800000;
  80196. // var DDSCAPS_COMPLEX = 0x8,
  80197. // DDSCAPS_MIPMAP = 0x400000,
  80198. // DDSCAPS_TEXTURE = 0x1000;
  80199. var DDSCAPS2_CUBEMAP = 0x200;
  80200. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  80201. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  80202. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  80203. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  80204. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  80205. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  80206. // DDSCAPS2_VOLUME = 0x200000;
  80207. var
  80208. //DDPF_ALPHAPIXELS = 0x1,
  80209. //DDPF_ALPHA = 0x2,
  80210. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  80211. //DDPF_YUV = 0x200,
  80212. DDPF_LUMINANCE = 0x20000;
  80213. function FourCCToInt32(value) {
  80214. return value.charCodeAt(0) +
  80215. (value.charCodeAt(1) << 8) +
  80216. (value.charCodeAt(2) << 16) +
  80217. (value.charCodeAt(3) << 24);
  80218. }
  80219. function Int32ToFourCC(value) {
  80220. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  80221. }
  80222. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  80223. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  80224. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  80225. var FOURCC_DX10 = FourCCToInt32("DX10");
  80226. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  80227. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  80228. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  80229. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  80230. var headerLengthInt = 31; // The header length in 32 bit ints
  80231. // Offsets into the header array
  80232. var off_magic = 0;
  80233. var off_size = 1;
  80234. var off_flags = 2;
  80235. var off_height = 3;
  80236. var off_width = 4;
  80237. var off_mipmapCount = 7;
  80238. var off_pfFlags = 20;
  80239. var off_pfFourCC = 21;
  80240. var off_RGBbpp = 22;
  80241. var off_RMask = 23;
  80242. var off_GMask = 24;
  80243. var off_BMask = 25;
  80244. var off_AMask = 26;
  80245. // var off_caps1 = 27;
  80246. var off_caps2 = 28;
  80247. // var off_caps3 = 29;
  80248. // var off_caps4 = 30;
  80249. var off_dxgiFormat = 32;
  80250. ;
  80251. var DDSTools = /** @class */ (function () {
  80252. function DDSTools() {
  80253. }
  80254. DDSTools.GetDDSInfo = function (arrayBuffer) {
  80255. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80256. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  80257. var mipmapCount = 1;
  80258. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  80259. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80260. }
  80261. var fourCC = header[off_pfFourCC];
  80262. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  80263. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80264. switch (fourCC) {
  80265. case FOURCC_D3DFMT_R16G16B16A16F:
  80266. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80267. break;
  80268. case FOURCC_D3DFMT_R32G32B32A32F:
  80269. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80270. break;
  80271. case FOURCC_DX10:
  80272. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  80273. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80274. break;
  80275. }
  80276. }
  80277. return {
  80278. width: header[off_width],
  80279. height: header[off_height],
  80280. mipmapCount: mipmapCount,
  80281. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  80282. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  80283. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  80284. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  80285. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  80286. dxgiFormat: dxgiFormat,
  80287. textureType: textureType
  80288. };
  80289. };
  80290. DDSTools._ToHalfFloat = function (value) {
  80291. if (!DDSTools._FloatView) {
  80292. DDSTools._FloatView = new Float32Array(1);
  80293. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  80294. }
  80295. DDSTools._FloatView[0] = value;
  80296. var x = DDSTools._Int32View[0];
  80297. var bits = (x >> 16) & 0x8000; /* Get the sign */
  80298. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  80299. var e = (x >> 23) & 0xff; /* Using int is faster here */
  80300. /* If zero, or denormal, or exponent underflows too much for a denormal
  80301. * half, return signed zero. */
  80302. if (e < 103) {
  80303. return bits;
  80304. }
  80305. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  80306. if (e > 142) {
  80307. bits |= 0x7c00;
  80308. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  80309. * not Inf, so make sure we set one mantissa bit too. */
  80310. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  80311. return bits;
  80312. }
  80313. /* If exponent underflows but not too much, return a denormal */
  80314. if (e < 113) {
  80315. m |= 0x0800;
  80316. /* Extra rounding may overflow and set mantissa to 0 and exponent
  80317. * to 1, which is OK. */
  80318. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  80319. return bits;
  80320. }
  80321. bits |= ((e - 112) << 10) | (m >> 1);
  80322. bits += m & 1;
  80323. return bits;
  80324. };
  80325. DDSTools._FromHalfFloat = function (value) {
  80326. var s = (value & 0x8000) >> 15;
  80327. var e = (value & 0x7C00) >> 10;
  80328. var f = value & 0x03FF;
  80329. if (e === 0) {
  80330. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  80331. }
  80332. else if (e == 0x1F) {
  80333. return f ? NaN : ((s ? -1 : 1) * Infinity);
  80334. }
  80335. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  80336. };
  80337. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80338. var destArray = new Float32Array(dataLength);
  80339. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80340. var index = 0;
  80341. for (var y = 0; y < height; y++) {
  80342. for (var x = 0; x < width; x++) {
  80343. var srcPos = (x + y * width) * 4;
  80344. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80345. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80346. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80347. if (DDSTools.StoreLODInAlphaChannel) {
  80348. destArray[index + 3] = lod;
  80349. }
  80350. else {
  80351. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80352. }
  80353. index += 4;
  80354. }
  80355. }
  80356. return destArray;
  80357. };
  80358. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80359. if (DDSTools.StoreLODInAlphaChannel) {
  80360. var destArray = new Uint16Array(dataLength);
  80361. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80362. var index = 0;
  80363. for (var y = 0; y < height; y++) {
  80364. for (var x = 0; x < width; x++) {
  80365. var srcPos = (x + y * width) * 4;
  80366. destArray[index] = srcData[srcPos];
  80367. destArray[index + 1] = srcData[srcPos + 1];
  80368. destArray[index + 2] = srcData[srcPos + 2];
  80369. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80370. index += 4;
  80371. }
  80372. }
  80373. return destArray;
  80374. }
  80375. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80376. };
  80377. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80378. if (DDSTools.StoreLODInAlphaChannel) {
  80379. var destArray = new Float32Array(dataLength);
  80380. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80381. var index = 0;
  80382. for (var y = 0; y < height; y++) {
  80383. for (var x = 0; x < width; x++) {
  80384. var srcPos = (x + y * width) * 4;
  80385. destArray[index] = srcData[srcPos];
  80386. destArray[index + 1] = srcData[srcPos + 1];
  80387. destArray[index + 2] = srcData[srcPos + 2];
  80388. destArray[index + 3] = lod;
  80389. index += 4;
  80390. }
  80391. }
  80392. return destArray;
  80393. }
  80394. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80395. };
  80396. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80397. var destArray = new Uint8Array(dataLength);
  80398. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80399. var index = 0;
  80400. for (var y = 0; y < height; y++) {
  80401. for (var x = 0; x < width; x++) {
  80402. var srcPos = (x + y * width) * 4;
  80403. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80404. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80405. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80406. if (DDSTools.StoreLODInAlphaChannel) {
  80407. destArray[index + 3] = lod;
  80408. }
  80409. else {
  80410. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80411. }
  80412. index += 4;
  80413. }
  80414. }
  80415. return destArray;
  80416. };
  80417. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80418. var destArray = new Uint8Array(dataLength);
  80419. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80420. var index = 0;
  80421. for (var y = 0; y < height; y++) {
  80422. for (var x = 0; x < width; x++) {
  80423. var srcPos = (x + y * width) * 4;
  80424. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80425. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80426. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80427. if (DDSTools.StoreLODInAlphaChannel) {
  80428. destArray[index + 3] = lod;
  80429. }
  80430. else {
  80431. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80432. }
  80433. index += 4;
  80434. }
  80435. }
  80436. return destArray;
  80437. };
  80438. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80439. var byteArray = new Uint8Array(dataLength);
  80440. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80441. var index = 0;
  80442. for (var y = 0; y < height; y++) {
  80443. for (var x = 0; x < width; x++) {
  80444. var srcPos = (x + y * width) * 4;
  80445. byteArray[index] = srcData[srcPos + rOffset];
  80446. byteArray[index + 1] = srcData[srcPos + gOffset];
  80447. byteArray[index + 2] = srcData[srcPos + bOffset];
  80448. byteArray[index + 3] = srcData[srcPos + aOffset];
  80449. index += 4;
  80450. }
  80451. }
  80452. return byteArray;
  80453. };
  80454. DDSTools._ExtractLongWordOrder = function (value) {
  80455. if (value === 0 || value === 255 || value === -16777216) {
  80456. return 0;
  80457. }
  80458. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80459. };
  80460. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80461. var byteArray = new Uint8Array(dataLength);
  80462. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80463. var index = 0;
  80464. for (var y = 0; y < height; y++) {
  80465. for (var x = 0; x < width; x++) {
  80466. var srcPos = (x + y * width) * 3;
  80467. byteArray[index] = srcData[srcPos + rOffset];
  80468. byteArray[index + 1] = srcData[srcPos + gOffset];
  80469. byteArray[index + 2] = srcData[srcPos + bOffset];
  80470. index += 3;
  80471. }
  80472. }
  80473. return byteArray;
  80474. };
  80475. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80476. var byteArray = new Uint8Array(dataLength);
  80477. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80478. var index = 0;
  80479. for (var y = 0; y < height; y++) {
  80480. for (var x = 0; x < width; x++) {
  80481. var srcPos = (x + y * width);
  80482. byteArray[index] = srcData[srcPos];
  80483. index++;
  80484. }
  80485. }
  80486. return byteArray;
  80487. };
  80488. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80489. if (lodIndex === void 0) { lodIndex = -1; }
  80490. var ext = engine.getCaps().s3tc;
  80491. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80492. var fourCC, width, height, dataLength = 0, dataOffset;
  80493. var byteArray, mipmapCount, mip;
  80494. var internalFormat = 0;
  80495. var format = 0;
  80496. var blockBytes = 1;
  80497. if (header[off_magic] !== DDS_MAGIC) {
  80498. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80499. return;
  80500. }
  80501. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80502. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80503. return;
  80504. }
  80505. if (info.isCompressed && !ext) {
  80506. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80507. return;
  80508. }
  80509. var bpp = header[off_RGBbpp];
  80510. dataOffset = header[off_size] + 4;
  80511. var computeFormats = false;
  80512. if (info.isFourCC) {
  80513. fourCC = header[off_pfFourCC];
  80514. switch (fourCC) {
  80515. case FOURCC_DXT1:
  80516. blockBytes = 8;
  80517. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80518. break;
  80519. case FOURCC_DXT3:
  80520. blockBytes = 16;
  80521. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80522. break;
  80523. case FOURCC_DXT5:
  80524. blockBytes = 16;
  80525. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80526. break;
  80527. case FOURCC_D3DFMT_R16G16B16A16F:
  80528. computeFormats = true;
  80529. break;
  80530. case FOURCC_D3DFMT_R32G32B32A32F:
  80531. computeFormats = true;
  80532. break;
  80533. case FOURCC_DX10:
  80534. // There is an additionnal header so dataOffset need to be changed
  80535. dataOffset += 5 * 4; // 5 uints
  80536. var supported = false;
  80537. switch (info.dxgiFormat) {
  80538. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80539. computeFormats = true;
  80540. supported = true;
  80541. break;
  80542. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80543. info.isRGB = true;
  80544. info.isFourCC = false;
  80545. bpp = 32;
  80546. supported = true;
  80547. break;
  80548. }
  80549. if (supported) {
  80550. break;
  80551. }
  80552. default:
  80553. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80554. return;
  80555. }
  80556. }
  80557. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80558. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80559. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80560. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80561. if (computeFormats) {
  80562. format = engine._getWebGLTextureType(info.textureType);
  80563. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80564. }
  80565. mipmapCount = 1;
  80566. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80567. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80568. }
  80569. for (var face = 0; face < faces; face++) {
  80570. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80571. width = header[off_width];
  80572. height = header[off_height];
  80573. for (mip = 0; mip < mipmapCount; ++mip) {
  80574. if (lodIndex === -1 || lodIndex === mip) {
  80575. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80576. var i = (lodIndex === -1) ? mip : 0;
  80577. if (!info.isCompressed && info.isFourCC) {
  80578. dataLength = width * height * 4;
  80579. var floatArray = null;
  80580. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80581. if (bpp === 128) {
  80582. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80583. }
  80584. else if (bpp === 64) {
  80585. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80586. }
  80587. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80588. format = engine._getWebGLTextureType(info.textureType);
  80589. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80590. }
  80591. else {
  80592. if (bpp === 128) {
  80593. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80594. }
  80595. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80596. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80597. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80598. format = engine._getWebGLTextureType(info.textureType);
  80599. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80600. }
  80601. else {
  80602. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80603. }
  80604. }
  80605. if (floatArray) {
  80606. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80607. }
  80608. }
  80609. else if (info.isRGB) {
  80610. if (bpp === 24) {
  80611. dataLength = width * height * 3;
  80612. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80613. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80614. }
  80615. else {
  80616. dataLength = width * height * 4;
  80617. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80618. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80619. }
  80620. }
  80621. else if (info.isLuminance) {
  80622. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80623. var unpaddedRowSize = width;
  80624. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80625. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80626. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80627. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80628. }
  80629. else {
  80630. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80631. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80632. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80633. }
  80634. }
  80635. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80636. width *= 0.5;
  80637. height *= 0.5;
  80638. width = Math.max(1.0, width);
  80639. height = Math.max(1.0, height);
  80640. }
  80641. if (currentFace !== undefined) {
  80642. // Loading a single face
  80643. break;
  80644. }
  80645. }
  80646. };
  80647. DDSTools.StoreLODInAlphaChannel = false;
  80648. return DDSTools;
  80649. }());
  80650. BABYLON.DDSTools = DDSTools;
  80651. })(BABYLON || (BABYLON = {}));
  80652. //# sourceMappingURL=babylon.dds.js.map
  80653. "use strict";
  80654. var BABYLON;
  80655. (function (BABYLON) {
  80656. /**
  80657. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80658. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80659. */
  80660. var KhronosTextureContainer = /** @class */ (function () {
  80661. /**
  80662. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80663. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80664. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80665. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80666. */
  80667. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80668. this.arrayBuffer = arrayBuffer;
  80669. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80670. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80671. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80672. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80673. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80674. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80675. BABYLON.Tools.Error("texture missing KTX identifier");
  80676. return;
  80677. }
  80678. // load the reset of the header in native 32 bit int
  80679. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80680. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80681. var oppositeEndianess = header[0] === 0x01020304;
  80682. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80683. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80684. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80685. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80686. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80687. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80688. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80689. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80690. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80691. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80692. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80693. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80694. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80695. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80696. if (this.glType !== 0) {
  80697. BABYLON.Tools.Error("only compressed formats currently supported");
  80698. return;
  80699. }
  80700. else {
  80701. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80702. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80703. }
  80704. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80705. BABYLON.Tools.Error("only 2D textures currently supported");
  80706. return;
  80707. }
  80708. if (this.numberOfArrayElements !== 0) {
  80709. BABYLON.Tools.Error("texture arrays not currently supported");
  80710. return;
  80711. }
  80712. if (this.numberOfFaces !== facesExpected) {
  80713. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80714. return;
  80715. }
  80716. // we now have a completely validated file, so could use existence of loadType as success
  80717. // would need to make this more elaborate & adjust checks above to support more than one load type
  80718. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80719. }
  80720. // not as fast hardware based, but will probably never need to use
  80721. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80722. return ((val & 0xFF) << 24)
  80723. | ((val & 0xFF00) << 8)
  80724. | ((val >> 8) & 0xFF00)
  80725. | ((val >> 24) & 0xFF);
  80726. };
  80727. /**
  80728. * It is assumed that the texture has already been created & is currently bound
  80729. */
  80730. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80731. switch (this.loadType) {
  80732. case KhronosTextureContainer.COMPRESSED_2D:
  80733. this._upload2DCompressedLevels(gl, loadMipmaps);
  80734. break;
  80735. case KhronosTextureContainer.TEX_2D:
  80736. case KhronosTextureContainer.COMPRESSED_3D:
  80737. case KhronosTextureContainer.TEX_3D:
  80738. }
  80739. };
  80740. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80741. // initialize width & height for level 1
  80742. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80743. var width = this.pixelWidth;
  80744. var height = this.pixelHeight;
  80745. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80746. for (var level = 0; level < mipmapCount; level++) {
  80747. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80748. for (var face = 0; face < this.numberOfFaces; face++) {
  80749. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80750. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80751. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80752. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80753. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80754. }
  80755. width = Math.max(1.0, width * 0.5);
  80756. height = Math.max(1.0, height * 0.5);
  80757. }
  80758. };
  80759. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80760. // load types
  80761. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80762. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80763. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80764. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80765. return KhronosTextureContainer;
  80766. }());
  80767. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80768. })(BABYLON || (BABYLON = {}));
  80769. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80770. "use strict";
  80771. var BABYLON;
  80772. (function (BABYLON) {
  80773. var Debug = /** @class */ (function () {
  80774. function Debug() {
  80775. }
  80776. Debug.AxesViewer = /** @class */ (function () {
  80777. function AxesViewer(scene, scaleLines) {
  80778. if (scaleLines === void 0) { scaleLines = 1; }
  80779. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80780. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80781. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80782. this.scaleLines = 1;
  80783. this.scaleLines = scaleLines;
  80784. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80785. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80786. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80787. this._xmesh.renderingGroupId = 2;
  80788. this._ymesh.renderingGroupId = 2;
  80789. this._zmesh.renderingGroupId = 2;
  80790. this._xmesh.material.checkReadyOnlyOnce = true;
  80791. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80792. this._ymesh.material.checkReadyOnlyOnce = true;
  80793. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80794. this._zmesh.material.checkReadyOnlyOnce = true;
  80795. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80796. this.scene = scene;
  80797. }
  80798. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80799. var scaleLines = this.scaleLines;
  80800. if (this._xmesh) {
  80801. this._xmesh.position.copyFrom(position);
  80802. }
  80803. if (this._ymesh) {
  80804. this._ymesh.position.copyFrom(position);
  80805. }
  80806. if (this._zmesh) {
  80807. this._zmesh.position.copyFrom(position);
  80808. }
  80809. var point2 = this._xline[1];
  80810. point2.x = xaxis.x * scaleLines;
  80811. point2.y = xaxis.y * scaleLines;
  80812. point2.z = xaxis.z * scaleLines;
  80813. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80814. point2 = this._yline[1];
  80815. point2.x = yaxis.x * scaleLines;
  80816. point2.y = yaxis.y * scaleLines;
  80817. point2.z = yaxis.z * scaleLines;
  80818. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80819. point2 = this._zline[1];
  80820. point2.x = zaxis.x * scaleLines;
  80821. point2.y = zaxis.y * scaleLines;
  80822. point2.z = zaxis.z * scaleLines;
  80823. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80824. };
  80825. AxesViewer.prototype.dispose = function () {
  80826. if (this._xmesh) {
  80827. this._xmesh.dispose();
  80828. }
  80829. if (this._ymesh) {
  80830. this._ymesh.dispose();
  80831. }
  80832. if (this._zmesh) {
  80833. this._zmesh.dispose();
  80834. }
  80835. this._xmesh = null;
  80836. this._ymesh = null;
  80837. this._zmesh = null;
  80838. this.scene = null;
  80839. };
  80840. return AxesViewer;
  80841. }());
  80842. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80843. __extends(BoneAxesViewer, _super);
  80844. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80845. if (scaleLines === void 0) { scaleLines = 1; }
  80846. var _this = _super.call(this, scene, scaleLines) || this;
  80847. _this.pos = BABYLON.Vector3.Zero();
  80848. _this.xaxis = BABYLON.Vector3.Zero();
  80849. _this.yaxis = BABYLON.Vector3.Zero();
  80850. _this.zaxis = BABYLON.Vector3.Zero();
  80851. _this.mesh = mesh;
  80852. _this.bone = bone;
  80853. return _this;
  80854. }
  80855. BoneAxesViewer.prototype.update = function () {
  80856. if (!this.mesh || !this.bone) {
  80857. return;
  80858. }
  80859. var bone = this.bone;
  80860. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80861. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80862. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80863. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80864. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80865. };
  80866. BoneAxesViewer.prototype.dispose = function () {
  80867. if (this.mesh) {
  80868. this.mesh = null;
  80869. this.bone = null;
  80870. _super.prototype.dispose.call(this);
  80871. }
  80872. };
  80873. return BoneAxesViewer;
  80874. }(Debug.AxesViewer));
  80875. Debug.PhysicsViewer = /** @class */ (function () {
  80876. function PhysicsViewer(scene) {
  80877. this._impostors = [];
  80878. this._meshes = [];
  80879. this._numMeshes = 0;
  80880. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80881. var physicEngine = this._scene.getPhysicsEngine();
  80882. if (physicEngine) {
  80883. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80884. }
  80885. }
  80886. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80887. var plugin = this._physicsEnginePlugin;
  80888. for (var i = 0; i < this._numMeshes; i++) {
  80889. var impostor = this._impostors[i];
  80890. if (!impostor) {
  80891. continue;
  80892. }
  80893. if (impostor.isDisposed) {
  80894. this.hideImpostor(this._impostors[i--]);
  80895. }
  80896. else {
  80897. var mesh = this._meshes[i];
  80898. if (mesh && plugin) {
  80899. plugin.syncMeshWithImpostor(mesh, impostor);
  80900. }
  80901. }
  80902. }
  80903. };
  80904. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80905. if (!this._scene) {
  80906. return;
  80907. }
  80908. for (var i = 0; i < this._numMeshes; i++) {
  80909. if (this._impostors[i] == impostor) {
  80910. return;
  80911. }
  80912. }
  80913. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80914. if (debugMesh) {
  80915. this._impostors[this._numMeshes] = impostor;
  80916. this._meshes[this._numMeshes] = debugMesh;
  80917. if (this._numMeshes === 0) {
  80918. this._renderFunction = this._updateDebugMeshes.bind(this);
  80919. this._scene.registerBeforeRender(this._renderFunction);
  80920. }
  80921. this._numMeshes++;
  80922. }
  80923. };
  80924. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80925. if (!impostor || !this._scene) {
  80926. return;
  80927. }
  80928. var removed = false;
  80929. for (var i = 0; i < this._numMeshes; i++) {
  80930. if (this._impostors[i] == impostor) {
  80931. var mesh = this._meshes[i];
  80932. if (!mesh) {
  80933. continue;
  80934. }
  80935. this._scene.removeMesh(mesh);
  80936. mesh.dispose();
  80937. this._numMeshes--;
  80938. if (this._numMeshes > 0) {
  80939. this._meshes[i] = this._meshes[this._numMeshes];
  80940. this._impostors[i] = this._impostors[this._numMeshes];
  80941. this._meshes[this._numMeshes] = null;
  80942. this._impostors[this._numMeshes] = null;
  80943. }
  80944. else {
  80945. this._meshes[0] = null;
  80946. this._impostors[0] = null;
  80947. }
  80948. removed = true;
  80949. break;
  80950. }
  80951. }
  80952. if (removed && this._numMeshes === 0) {
  80953. this._scene.unregisterBeforeRender(this._renderFunction);
  80954. }
  80955. };
  80956. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80957. if (!this._debugMaterial) {
  80958. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80959. this._debugMaterial.wireframe = true;
  80960. }
  80961. return this._debugMaterial;
  80962. };
  80963. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80964. if (!this._debugBoxMesh) {
  80965. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80966. this._debugBoxMesh.renderingGroupId = 1;
  80967. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80968. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80969. scene.removeMesh(this._debugBoxMesh);
  80970. }
  80971. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80972. };
  80973. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80974. if (!this._debugSphereMesh) {
  80975. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80976. this._debugSphereMesh.renderingGroupId = 1;
  80977. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80978. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80979. scene.removeMesh(this._debugSphereMesh);
  80980. }
  80981. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80982. };
  80983. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80984. var mesh = null;
  80985. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80986. mesh = this._getDebugBoxMesh(scene);
  80987. impostor.getBoxSizeToRef(mesh.scaling);
  80988. }
  80989. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80990. mesh = this._getDebugSphereMesh(scene);
  80991. var radius = impostor.getRadius();
  80992. mesh.scaling.x = radius * 2;
  80993. mesh.scaling.y = radius * 2;
  80994. mesh.scaling.z = radius * 2;
  80995. }
  80996. return mesh;
  80997. };
  80998. PhysicsViewer.prototype.dispose = function () {
  80999. for (var i = 0; i < this._numMeshes; i++) {
  81000. this.hideImpostor(this._impostors[i]);
  81001. }
  81002. if (this._debugBoxMesh) {
  81003. this._debugBoxMesh.dispose();
  81004. }
  81005. if (this._debugSphereMesh) {
  81006. this._debugSphereMesh.dispose();
  81007. }
  81008. if (this._debugMaterial) {
  81009. this._debugMaterial.dispose();
  81010. }
  81011. this._impostors.length = 0;
  81012. this._scene = null;
  81013. this._physicsEnginePlugin = null;
  81014. };
  81015. return PhysicsViewer;
  81016. }());
  81017. Debug.SkeletonViewer = /** @class */ (function () {
  81018. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  81019. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  81020. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  81021. this.skeleton = skeleton;
  81022. this.mesh = mesh;
  81023. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  81024. this.renderingGroupId = renderingGroupId;
  81025. this.color = BABYLON.Color3.White();
  81026. this._debugLines = new Array();
  81027. this._isEnabled = false;
  81028. this._scene = scene;
  81029. this.update();
  81030. this._renderFunction = this.update.bind(this);
  81031. }
  81032. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  81033. get: function () {
  81034. return this._isEnabled;
  81035. },
  81036. set: function (value) {
  81037. if (this._isEnabled === value) {
  81038. return;
  81039. }
  81040. this._isEnabled = value;
  81041. if (value) {
  81042. this._scene.registerBeforeRender(this._renderFunction);
  81043. }
  81044. else {
  81045. this._scene.unregisterBeforeRender(this._renderFunction);
  81046. }
  81047. },
  81048. enumerable: true,
  81049. configurable: true
  81050. });
  81051. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  81052. if (x === void 0) { x = 0; }
  81053. if (y === void 0) { y = 0; }
  81054. if (z === void 0) { z = 0; }
  81055. var tmat = BABYLON.Tmp.Matrix[0];
  81056. var parentBone = bone.getParent();
  81057. tmat.copyFrom(bone.getLocalMatrix());
  81058. if (x !== 0 || y !== 0 || z !== 0) {
  81059. var tmat2 = BABYLON.Tmp.Matrix[1];
  81060. BABYLON.Matrix.IdentityToRef(tmat2);
  81061. tmat2.m[12] = x;
  81062. tmat2.m[13] = y;
  81063. tmat2.m[14] = z;
  81064. tmat2.multiplyToRef(tmat, tmat);
  81065. }
  81066. if (parentBone) {
  81067. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  81068. }
  81069. tmat.multiplyToRef(meshMat, tmat);
  81070. position.x = tmat.m[12];
  81071. position.y = tmat.m[13];
  81072. position.z = tmat.m[14];
  81073. };
  81074. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  81075. var len = bones.length;
  81076. var meshPos = this.mesh.position;
  81077. for (var i = 0; i < len; i++) {
  81078. var bone = bones[i];
  81079. var points = this._debugLines[i];
  81080. if (!points) {
  81081. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81082. this._debugLines[i] = points;
  81083. }
  81084. this._getBonePosition(points[0], bone, meshMat);
  81085. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  81086. points[0].subtractInPlace(meshPos);
  81087. points[1].subtractInPlace(meshPos);
  81088. }
  81089. };
  81090. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  81091. var len = bones.length;
  81092. var boneNum = 0;
  81093. var meshPos = this.mesh.position;
  81094. for (var i = len - 1; i >= 0; i--) {
  81095. var childBone = bones[i];
  81096. var parentBone = childBone.getParent();
  81097. if (!parentBone) {
  81098. continue;
  81099. }
  81100. var points = this._debugLines[boneNum];
  81101. if (!points) {
  81102. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81103. this._debugLines[boneNum] = points;
  81104. }
  81105. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  81106. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  81107. points[0].subtractInPlace(meshPos);
  81108. points[1].subtractInPlace(meshPos);
  81109. boneNum++;
  81110. }
  81111. };
  81112. SkeletonViewer.prototype.update = function () {
  81113. if (this.autoUpdateBonesMatrices) {
  81114. this.skeleton.computeAbsoluteTransforms();
  81115. }
  81116. if (this.skeleton.bones[0].length === undefined) {
  81117. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  81118. }
  81119. else {
  81120. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  81121. }
  81122. if (!this._debugMesh) {
  81123. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  81124. this._debugMesh.renderingGroupId = this.renderingGroupId;
  81125. }
  81126. else {
  81127. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  81128. }
  81129. this._debugMesh.position.copyFrom(this.mesh.position);
  81130. this._debugMesh.color = this.color;
  81131. };
  81132. SkeletonViewer.prototype.dispose = function () {
  81133. if (this._debugMesh) {
  81134. this.isEnabled = false;
  81135. this._debugMesh.dispose();
  81136. this._debugMesh = null;
  81137. }
  81138. };
  81139. return SkeletonViewer;
  81140. }());
  81141. return Debug;
  81142. }());
  81143. BABYLON.Debug = Debug;
  81144. })(BABYLON || (BABYLON = {}));
  81145. //# sourceMappingURL=babylon.debugModules.js.map
  81146. "use strict";
  81147. var BABYLON;
  81148. (function (BABYLON) {
  81149. var RayHelper = /** @class */ (function () {
  81150. function RayHelper(ray) {
  81151. this.ray = ray;
  81152. }
  81153. RayHelper.CreateAndShow = function (ray, scene, color) {
  81154. var helper = new RayHelper(ray);
  81155. helper.show(scene, color);
  81156. return helper;
  81157. };
  81158. RayHelper.prototype.show = function (scene, color) {
  81159. if (!this._renderFunction && this.ray) {
  81160. var ray = this.ray;
  81161. this._renderFunction = this._render.bind(this);
  81162. this._scene = scene;
  81163. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  81164. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  81165. if (this._renderFunction) {
  81166. this._scene.registerBeforeRender(this._renderFunction);
  81167. }
  81168. }
  81169. if (color && this._renderLine) {
  81170. this._renderLine.color.copyFrom(color);
  81171. }
  81172. };
  81173. RayHelper.prototype.hide = function () {
  81174. if (this._renderFunction && this._scene) {
  81175. this._scene.unregisterBeforeRender(this._renderFunction);
  81176. this._scene = null;
  81177. this._renderFunction = null;
  81178. if (this._renderLine) {
  81179. this._renderLine.dispose();
  81180. this._renderLine = null;
  81181. }
  81182. this._renderPoints = [];
  81183. }
  81184. };
  81185. RayHelper.prototype._render = function () {
  81186. var ray = this.ray;
  81187. if (!ray) {
  81188. return;
  81189. }
  81190. var point = this._renderPoints[1];
  81191. var len = Math.min(ray.length, 1000000);
  81192. point.copyFrom(ray.direction);
  81193. point.scaleInPlace(len);
  81194. point.addInPlace(ray.origin);
  81195. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  81196. };
  81197. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  81198. this._attachedToMesh = mesh;
  81199. var ray = this.ray;
  81200. if (!ray) {
  81201. return;
  81202. }
  81203. if (!ray.direction) {
  81204. ray.direction = BABYLON.Vector3.Zero();
  81205. }
  81206. if (!ray.origin) {
  81207. ray.origin = BABYLON.Vector3.Zero();
  81208. }
  81209. if (length) {
  81210. ray.length = length;
  81211. }
  81212. if (!meshSpaceOrigin) {
  81213. meshSpaceOrigin = BABYLON.Vector3.Zero();
  81214. }
  81215. if (!meshSpaceDirection) {
  81216. // -1 so that this will work with Mesh.lookAt
  81217. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  81218. }
  81219. if (!this._meshSpaceDirection) {
  81220. this._meshSpaceDirection = meshSpaceDirection.clone();
  81221. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  81222. }
  81223. else {
  81224. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  81225. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  81226. }
  81227. if (!this._updateToMeshFunction) {
  81228. this._updateToMeshFunction = this._updateToMesh.bind(this);
  81229. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  81230. }
  81231. this._updateToMesh();
  81232. };
  81233. RayHelper.prototype.detachFromMesh = function () {
  81234. if (this._attachedToMesh) {
  81235. if (this._updateToMeshFunction) {
  81236. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  81237. }
  81238. this._attachedToMesh = null;
  81239. this._updateToMeshFunction = null;
  81240. }
  81241. };
  81242. RayHelper.prototype._updateToMesh = function () {
  81243. var ray = this.ray;
  81244. if (!this._attachedToMesh || !ray) {
  81245. return;
  81246. }
  81247. if (this._attachedToMesh._isDisposed) {
  81248. this.detachFromMesh();
  81249. return;
  81250. }
  81251. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  81252. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  81253. };
  81254. RayHelper.prototype.dispose = function () {
  81255. this.hide();
  81256. this.detachFromMesh();
  81257. this.ray = null;
  81258. };
  81259. return RayHelper;
  81260. }());
  81261. BABYLON.RayHelper = RayHelper;
  81262. })(BABYLON || (BABYLON = {}));
  81263. //# sourceMappingURL=babylon.rayHelper.js.map
  81264. "use strict";
  81265. var BABYLON;
  81266. (function (BABYLON) {
  81267. // load the inspector using require, if not present in the global namespace.
  81268. var DebugLayer = /** @class */ (function () {
  81269. function DebugLayer(scene) {
  81270. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81271. this._scene = scene;
  81272. // load inspector using require, if it doesn't exist on the global namespace.
  81273. }
  81274. /** Creates the inspector window. */
  81275. DebugLayer.prototype._createInspector = function (config) {
  81276. if (config === void 0) { config = {}; }
  81277. var popup = config.popup || false;
  81278. var initialTab = config.initialTab || 0;
  81279. var parentElement = config.parentElement || null;
  81280. if (!this._inspector) {
  81281. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81282. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  81283. } // else nothing to do,; instance is already existing
  81284. };
  81285. DebugLayer.prototype.isVisible = function () {
  81286. if (!this._inspector) {
  81287. return false;
  81288. }
  81289. return true;
  81290. };
  81291. DebugLayer.prototype.hide = function () {
  81292. if (this._inspector) {
  81293. try {
  81294. this._inspector.dispose();
  81295. }
  81296. catch (e) {
  81297. // If the inspector has been removed directly from the inspector tool
  81298. }
  81299. this._inspector = null;
  81300. }
  81301. };
  81302. DebugLayer.prototype.show = function (config) {
  81303. if (config === void 0) { config = {}; }
  81304. if (typeof this.BJSINSPECTOR == 'undefined') {
  81305. // Load inspector and add it to the DOM
  81306. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  81307. }
  81308. else {
  81309. // Otherwise creates the inspector
  81310. this._createInspector(config);
  81311. }
  81312. };
  81313. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  81314. return DebugLayer;
  81315. }());
  81316. BABYLON.DebugLayer = DebugLayer;
  81317. })(BABYLON || (BABYLON = {}));
  81318. //# sourceMappingURL=babylon.debugLayer.js.map
  81319. "use strict";
  81320. var BABYLON;
  81321. (function (BABYLON) {
  81322. var BoundingBoxRenderer = /** @class */ (function () {
  81323. function BoundingBoxRenderer(scene) {
  81324. this.frontColor = new BABYLON.Color3(1, 1, 1);
  81325. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  81326. this.showBackLines = true;
  81327. this.renderList = new BABYLON.SmartArray(32);
  81328. this._vertexBuffers = {};
  81329. this._scene = scene;
  81330. }
  81331. BoundingBoxRenderer.prototype._prepareRessources = function () {
  81332. if (this._colorShader) {
  81333. return;
  81334. }
  81335. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  81336. attributes: [BABYLON.VertexBuffer.PositionKind],
  81337. uniforms: ["world", "viewProjection", "color"]
  81338. });
  81339. var engine = this._scene.getEngine();
  81340. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  81341. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  81342. this._createIndexBuffer();
  81343. };
  81344. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81345. var engine = this._scene.getEngine();
  81346. 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]);
  81347. };
  81348. BoundingBoxRenderer.prototype._rebuild = function () {
  81349. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81350. if (vb) {
  81351. vb._rebuild();
  81352. }
  81353. this._createIndexBuffer();
  81354. };
  81355. BoundingBoxRenderer.prototype.reset = function () {
  81356. this.renderList.reset();
  81357. };
  81358. BoundingBoxRenderer.prototype.render = function () {
  81359. if (this.renderList.length === 0) {
  81360. return;
  81361. }
  81362. this._prepareRessources();
  81363. if (!this._colorShader.isReady()) {
  81364. return;
  81365. }
  81366. var engine = this._scene.getEngine();
  81367. engine.setDepthWrite(false);
  81368. this._colorShader._preBind();
  81369. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81370. var boundingBox = this.renderList.data[boundingBoxIndex];
  81371. var min = boundingBox.minimum;
  81372. var max = boundingBox.maximum;
  81373. var diff = max.subtract(min);
  81374. var median = min.add(diff.scale(0.5));
  81375. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81376. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81377. .multiply(boundingBox.getWorldMatrix());
  81378. // VBOs
  81379. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81380. if (this.showBackLines) {
  81381. // Back
  81382. engine.setDepthFunctionToGreaterOrEqual();
  81383. this._scene.resetCachedMaterial();
  81384. this._colorShader.setColor4("color", this.backColor.toColor4());
  81385. this._colorShader.bind(worldMatrix);
  81386. // Draw order
  81387. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81388. }
  81389. // Front
  81390. engine.setDepthFunctionToLess();
  81391. this._scene.resetCachedMaterial();
  81392. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81393. this._colorShader.bind(worldMatrix);
  81394. // Draw order
  81395. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81396. }
  81397. this._colorShader.unbind();
  81398. engine.setDepthFunctionToLessOrEqual();
  81399. engine.setDepthWrite(true);
  81400. };
  81401. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81402. this._prepareRessources();
  81403. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81404. return;
  81405. }
  81406. var engine = this._scene.getEngine();
  81407. engine.setDepthWrite(false);
  81408. engine.setColorWrite(false);
  81409. this._colorShader._preBind();
  81410. var boundingBox = mesh._boundingInfo.boundingBox;
  81411. var min = boundingBox.minimum;
  81412. var max = boundingBox.maximum;
  81413. var diff = max.subtract(min);
  81414. var median = min.add(diff.scale(0.5));
  81415. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81416. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81417. .multiply(boundingBox.getWorldMatrix());
  81418. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81419. engine.setDepthFunctionToLess();
  81420. this._scene.resetCachedMaterial();
  81421. this._colorShader.bind(worldMatrix);
  81422. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81423. this._colorShader.unbind();
  81424. engine.setDepthFunctionToLessOrEqual();
  81425. engine.setDepthWrite(true);
  81426. engine.setColorWrite(true);
  81427. };
  81428. BoundingBoxRenderer.prototype.dispose = function () {
  81429. if (!this._colorShader) {
  81430. return;
  81431. }
  81432. this.renderList.dispose();
  81433. this._colorShader.dispose();
  81434. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81435. if (buffer) {
  81436. buffer.dispose();
  81437. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81438. }
  81439. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81440. };
  81441. return BoundingBoxRenderer;
  81442. }());
  81443. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81444. })(BABYLON || (BABYLON = {}));
  81445. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81446. "use strict";
  81447. var BABYLON;
  81448. (function (BABYLON) {
  81449. var MorphTarget = /** @class */ (function () {
  81450. function MorphTarget(name, influence) {
  81451. if (influence === void 0) { influence = 0; }
  81452. this.name = name;
  81453. this.animations = new Array();
  81454. this._positions = null;
  81455. this._normals = null;
  81456. this._tangents = null;
  81457. this.onInfluenceChanged = new BABYLON.Observable();
  81458. this.influence = influence;
  81459. }
  81460. Object.defineProperty(MorphTarget.prototype, "influence", {
  81461. get: function () {
  81462. return this._influence;
  81463. },
  81464. set: function (influence) {
  81465. if (this._influence === influence) {
  81466. return;
  81467. }
  81468. var previous = this._influence;
  81469. this._influence = influence;
  81470. if (this.onInfluenceChanged.hasObservers) {
  81471. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81472. }
  81473. },
  81474. enumerable: true,
  81475. configurable: true
  81476. });
  81477. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81478. get: function () {
  81479. return !!this._positions;
  81480. },
  81481. enumerable: true,
  81482. configurable: true
  81483. });
  81484. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81485. get: function () {
  81486. return !!this._normals;
  81487. },
  81488. enumerable: true,
  81489. configurable: true
  81490. });
  81491. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81492. get: function () {
  81493. return !!this._tangents;
  81494. },
  81495. enumerable: true,
  81496. configurable: true
  81497. });
  81498. MorphTarget.prototype.setPositions = function (data) {
  81499. this._positions = data;
  81500. };
  81501. MorphTarget.prototype.getPositions = function () {
  81502. return this._positions;
  81503. };
  81504. MorphTarget.prototype.setNormals = function (data) {
  81505. this._normals = data;
  81506. };
  81507. MorphTarget.prototype.getNormals = function () {
  81508. return this._normals;
  81509. };
  81510. MorphTarget.prototype.setTangents = function (data) {
  81511. this._tangents = data;
  81512. };
  81513. MorphTarget.prototype.getTangents = function () {
  81514. return this._tangents;
  81515. };
  81516. /**
  81517. * Serializes the current target into a Serialization object.
  81518. * Returns the serialized object.
  81519. */
  81520. MorphTarget.prototype.serialize = function () {
  81521. var serializationObject = {};
  81522. serializationObject.name = this.name;
  81523. serializationObject.influence = this.influence;
  81524. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81525. if (this.hasNormals) {
  81526. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81527. }
  81528. if (this.hasTangents) {
  81529. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81530. }
  81531. // Animations
  81532. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81533. return serializationObject;
  81534. };
  81535. // Statics
  81536. MorphTarget.Parse = function (serializationObject) {
  81537. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81538. result.setPositions(serializationObject.positions);
  81539. if (serializationObject.normals) {
  81540. result.setNormals(serializationObject.normals);
  81541. }
  81542. if (serializationObject.tangents) {
  81543. result.setTangents(serializationObject.tangents);
  81544. }
  81545. // Animations
  81546. if (serializationObject.animations) {
  81547. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81548. var parsedAnimation = serializationObject.animations[animationIndex];
  81549. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81550. }
  81551. }
  81552. return result;
  81553. };
  81554. MorphTarget.FromMesh = function (mesh, name, influence) {
  81555. if (!name) {
  81556. name = mesh.name;
  81557. }
  81558. var result = new MorphTarget(name, influence);
  81559. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81560. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81561. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81562. }
  81563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81564. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81565. }
  81566. return result;
  81567. };
  81568. return MorphTarget;
  81569. }());
  81570. BABYLON.MorphTarget = MorphTarget;
  81571. })(BABYLON || (BABYLON = {}));
  81572. //# sourceMappingURL=babylon.morphTarget.js.map
  81573. "use strict";
  81574. var BABYLON;
  81575. (function (BABYLON) {
  81576. var MorphTargetManager = /** @class */ (function () {
  81577. function MorphTargetManager(scene) {
  81578. if (scene === void 0) { scene = null; }
  81579. this._targets = new Array();
  81580. this._targetObservable = new Array();
  81581. this._activeTargets = new BABYLON.SmartArray(16);
  81582. this._supportsNormals = false;
  81583. this._supportsTangents = false;
  81584. this._vertexCount = 0;
  81585. this._uniqueId = 0;
  81586. this._tempInfluences = new Array();
  81587. if (!scene) {
  81588. scene = BABYLON.Engine.LastCreatedScene;
  81589. }
  81590. this._scene = scene;
  81591. if (this._scene) {
  81592. this._scene.morphTargetManagers.push(this);
  81593. this._uniqueId = this._scene.getUniqueId();
  81594. }
  81595. }
  81596. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81597. get: function () {
  81598. return this._uniqueId;
  81599. },
  81600. enumerable: true,
  81601. configurable: true
  81602. });
  81603. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81604. get: function () {
  81605. return this._vertexCount;
  81606. },
  81607. enumerable: true,
  81608. configurable: true
  81609. });
  81610. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81611. get: function () {
  81612. return this._supportsNormals;
  81613. },
  81614. enumerable: true,
  81615. configurable: true
  81616. });
  81617. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81618. get: function () {
  81619. return this._supportsTangents;
  81620. },
  81621. enumerable: true,
  81622. configurable: true
  81623. });
  81624. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81625. get: function () {
  81626. return this._targets.length;
  81627. },
  81628. enumerable: true,
  81629. configurable: true
  81630. });
  81631. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81632. get: function () {
  81633. return this._activeTargets.length;
  81634. },
  81635. enumerable: true,
  81636. configurable: true
  81637. });
  81638. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81639. get: function () {
  81640. return this._influences;
  81641. },
  81642. enumerable: true,
  81643. configurable: true
  81644. });
  81645. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81646. return this._activeTargets.data[index];
  81647. };
  81648. MorphTargetManager.prototype.getTarget = function (index) {
  81649. return this._targets[index];
  81650. };
  81651. MorphTargetManager.prototype.addTarget = function (target) {
  81652. var _this = this;
  81653. this._targets.push(target);
  81654. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81655. _this._syncActiveTargets(needUpdate);
  81656. }));
  81657. this._syncActiveTargets(true);
  81658. };
  81659. MorphTargetManager.prototype.removeTarget = function (target) {
  81660. var index = this._targets.indexOf(target);
  81661. if (index >= 0) {
  81662. this._targets.splice(index, 1);
  81663. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81664. this._syncActiveTargets(true);
  81665. }
  81666. };
  81667. /**
  81668. * Serializes the current manager into a Serialization object.
  81669. * Returns the serialized object.
  81670. */
  81671. MorphTargetManager.prototype.serialize = function () {
  81672. var serializationObject = {};
  81673. serializationObject.id = this.uniqueId;
  81674. serializationObject.targets = [];
  81675. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81676. var target = _a[_i];
  81677. serializationObject.targets.push(target.serialize());
  81678. }
  81679. return serializationObject;
  81680. };
  81681. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81682. var influenceCount = 0;
  81683. this._activeTargets.reset();
  81684. this._supportsNormals = true;
  81685. this._supportsTangents = true;
  81686. this._vertexCount = 0;
  81687. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81688. var target = _a[_i];
  81689. this._activeTargets.push(target);
  81690. this._tempInfluences[influenceCount++] = target.influence;
  81691. var positions = target.getPositions();
  81692. if (positions) {
  81693. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81694. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81695. var vertexCount = positions.length / 3;
  81696. if (this._vertexCount === 0) {
  81697. this._vertexCount = vertexCount;
  81698. }
  81699. else if (this._vertexCount !== vertexCount) {
  81700. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81701. return;
  81702. }
  81703. }
  81704. }
  81705. if (!this._influences || this._influences.length !== influenceCount) {
  81706. this._influences = new Float32Array(influenceCount);
  81707. }
  81708. for (var index = 0; index < influenceCount; index++) {
  81709. this._influences[index] = this._tempInfluences[index];
  81710. }
  81711. if (needUpdate && this._scene) {
  81712. // Flag meshes as dirty to resync with the active targets
  81713. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81714. var mesh = _c[_b];
  81715. if (mesh.morphTargetManager === this) {
  81716. mesh._syncGeometryWithMorphTargetManager();
  81717. }
  81718. }
  81719. }
  81720. };
  81721. // Statics
  81722. MorphTargetManager.Parse = function (serializationObject, scene) {
  81723. var result = new MorphTargetManager(scene);
  81724. result._uniqueId = serializationObject.id;
  81725. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81726. var targetData = _a[_i];
  81727. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81728. }
  81729. return result;
  81730. };
  81731. return MorphTargetManager;
  81732. }());
  81733. BABYLON.MorphTargetManager = MorphTargetManager;
  81734. })(BABYLON || (BABYLON = {}));
  81735. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81736. "use strict";
  81737. var BABYLON;
  81738. (function (BABYLON) {
  81739. var Octree = /** @class */ (function () {
  81740. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81741. if (maxDepth === void 0) { maxDepth = 2; }
  81742. this.maxDepth = maxDepth;
  81743. this.dynamicContent = new Array();
  81744. this._maxBlockCapacity = maxBlockCapacity || 64;
  81745. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81746. this._creationFunc = creationFunc;
  81747. }
  81748. // Methods
  81749. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81750. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81751. };
  81752. Octree.prototype.addMesh = function (entry) {
  81753. for (var index = 0; index < this.blocks.length; index++) {
  81754. var block = this.blocks[index];
  81755. block.addEntry(entry);
  81756. }
  81757. };
  81758. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81759. this._selectionContent.reset();
  81760. for (var index = 0; index < this.blocks.length; index++) {
  81761. var block = this.blocks[index];
  81762. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81763. }
  81764. if (allowDuplicate) {
  81765. this._selectionContent.concat(this.dynamicContent);
  81766. }
  81767. else {
  81768. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81769. }
  81770. return this._selectionContent;
  81771. };
  81772. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81773. this._selectionContent.reset();
  81774. for (var index = 0; index < this.blocks.length; index++) {
  81775. var block = this.blocks[index];
  81776. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81777. }
  81778. if (allowDuplicate) {
  81779. this._selectionContent.concat(this.dynamicContent);
  81780. }
  81781. else {
  81782. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81783. }
  81784. return this._selectionContent;
  81785. };
  81786. Octree.prototype.intersectsRay = function (ray) {
  81787. this._selectionContent.reset();
  81788. for (var index = 0; index < this.blocks.length; index++) {
  81789. var block = this.blocks[index];
  81790. block.intersectsRay(ray, this._selectionContent);
  81791. }
  81792. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81793. return this._selectionContent;
  81794. };
  81795. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81796. target.blocks = new Array();
  81797. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81798. // Segmenting space
  81799. for (var x = 0; x < 2; x++) {
  81800. for (var y = 0; y < 2; y++) {
  81801. for (var z = 0; z < 2; z++) {
  81802. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81803. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81804. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81805. block.addEntries(entries);
  81806. target.blocks.push(block);
  81807. }
  81808. }
  81809. }
  81810. };
  81811. Octree.CreationFuncForMeshes = function (entry, block) {
  81812. var boundingInfo = entry.getBoundingInfo();
  81813. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81814. block.entries.push(entry);
  81815. }
  81816. };
  81817. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81818. var boundingInfo = entry.getBoundingInfo();
  81819. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81820. block.entries.push(entry);
  81821. }
  81822. };
  81823. return Octree;
  81824. }());
  81825. BABYLON.Octree = Octree;
  81826. })(BABYLON || (BABYLON = {}));
  81827. //# sourceMappingURL=babylon.octree.js.map
  81828. "use strict";
  81829. var BABYLON;
  81830. (function (BABYLON) {
  81831. var OctreeBlock = /** @class */ (function () {
  81832. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81833. this.entries = new Array();
  81834. this._boundingVectors = new Array();
  81835. this._capacity = capacity;
  81836. this._depth = depth;
  81837. this._maxDepth = maxDepth;
  81838. this._creationFunc = creationFunc;
  81839. this._minPoint = minPoint;
  81840. this._maxPoint = maxPoint;
  81841. this._boundingVectors.push(minPoint.clone());
  81842. this._boundingVectors.push(maxPoint.clone());
  81843. this._boundingVectors.push(minPoint.clone());
  81844. this._boundingVectors[2].x = maxPoint.x;
  81845. this._boundingVectors.push(minPoint.clone());
  81846. this._boundingVectors[3].y = maxPoint.y;
  81847. this._boundingVectors.push(minPoint.clone());
  81848. this._boundingVectors[4].z = maxPoint.z;
  81849. this._boundingVectors.push(maxPoint.clone());
  81850. this._boundingVectors[5].z = minPoint.z;
  81851. this._boundingVectors.push(maxPoint.clone());
  81852. this._boundingVectors[6].x = minPoint.x;
  81853. this._boundingVectors.push(maxPoint.clone());
  81854. this._boundingVectors[7].y = minPoint.y;
  81855. }
  81856. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81857. // Property
  81858. get: function () {
  81859. return this._capacity;
  81860. },
  81861. enumerable: true,
  81862. configurable: true
  81863. });
  81864. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81865. get: function () {
  81866. return this._minPoint;
  81867. },
  81868. enumerable: true,
  81869. configurable: true
  81870. });
  81871. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81872. get: function () {
  81873. return this._maxPoint;
  81874. },
  81875. enumerable: true,
  81876. configurable: true
  81877. });
  81878. // Methods
  81879. OctreeBlock.prototype.addEntry = function (entry) {
  81880. if (this.blocks) {
  81881. for (var index = 0; index < this.blocks.length; index++) {
  81882. var block = this.blocks[index];
  81883. block.addEntry(entry);
  81884. }
  81885. return;
  81886. }
  81887. this._creationFunc(entry, this);
  81888. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81889. this.createInnerBlocks();
  81890. }
  81891. };
  81892. OctreeBlock.prototype.addEntries = function (entries) {
  81893. for (var index = 0; index < entries.length; index++) {
  81894. var mesh = entries[index];
  81895. this.addEntry(mesh);
  81896. }
  81897. };
  81898. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81899. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81900. if (this.blocks) {
  81901. for (var index = 0; index < this.blocks.length; index++) {
  81902. var block = this.blocks[index];
  81903. block.select(frustumPlanes, selection, allowDuplicate);
  81904. }
  81905. return;
  81906. }
  81907. if (allowDuplicate) {
  81908. selection.concat(this.entries);
  81909. }
  81910. else {
  81911. selection.concatWithNoDuplicate(this.entries);
  81912. }
  81913. }
  81914. };
  81915. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81916. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81917. if (this.blocks) {
  81918. for (var index = 0; index < this.blocks.length; index++) {
  81919. var block = this.blocks[index];
  81920. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81921. }
  81922. return;
  81923. }
  81924. if (allowDuplicate) {
  81925. selection.concat(this.entries);
  81926. }
  81927. else {
  81928. selection.concatWithNoDuplicate(this.entries);
  81929. }
  81930. }
  81931. };
  81932. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81933. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81934. if (this.blocks) {
  81935. for (var index = 0; index < this.blocks.length; index++) {
  81936. var block = this.blocks[index];
  81937. block.intersectsRay(ray, selection);
  81938. }
  81939. return;
  81940. }
  81941. selection.concatWithNoDuplicate(this.entries);
  81942. }
  81943. };
  81944. OctreeBlock.prototype.createInnerBlocks = function () {
  81945. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81946. };
  81947. return OctreeBlock;
  81948. }());
  81949. BABYLON.OctreeBlock = OctreeBlock;
  81950. })(BABYLON || (BABYLON = {}));
  81951. //# sourceMappingURL=babylon.octreeBlock.js.map
  81952. "use strict";
  81953. var BABYLON;
  81954. (function (BABYLON) {
  81955. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81956. __extends(VRDistortionCorrectionPostProcess, _super);
  81957. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81958. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81959. 'LensCenter',
  81960. 'Scale',
  81961. 'ScaleIn',
  81962. 'HmdWarpParam'
  81963. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81964. _this._isRightEye = isRightEye;
  81965. _this._distortionFactors = vrMetrics.distortionK;
  81966. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81967. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81968. _this.adaptScaleToCurrentViewport = true;
  81969. _this.onSizeChangedObservable.add(function () {
  81970. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81971. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81972. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81973. });
  81974. _this.onApplyObservable.add(function (effect) {
  81975. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81976. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81977. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81978. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81979. });
  81980. return _this;
  81981. }
  81982. return VRDistortionCorrectionPostProcess;
  81983. }(BABYLON.PostProcess));
  81984. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81985. })(BABYLON || (BABYLON = {}));
  81986. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81987. "use strict";
  81988. var BABYLON;
  81989. (function (BABYLON) {
  81990. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81991. __extends(AnaglyphPostProcess, _super);
  81992. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81993. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81994. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81995. _this.onApplyObservable.add(function (effect) {
  81996. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81997. });
  81998. return _this;
  81999. }
  82000. return AnaglyphPostProcess;
  82001. }(BABYLON.PostProcess));
  82002. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  82003. })(BABYLON || (BABYLON = {}));
  82004. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  82005. "use strict";
  82006. var BABYLON;
  82007. (function (BABYLON) {
  82008. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  82009. __extends(StereoscopicInterlacePostProcess, _super);
  82010. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  82011. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  82012. _this._passedProcess = rigCameras[0]._rigPostProcess;
  82013. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  82014. _this.onSizeChangedObservable.add(function () {
  82015. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  82016. });
  82017. _this.onApplyObservable.add(function (effect) {
  82018. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  82019. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  82020. });
  82021. return _this;
  82022. }
  82023. return StereoscopicInterlacePostProcess;
  82024. }(BABYLON.PostProcess));
  82025. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  82026. })(BABYLON || (BABYLON = {}));
  82027. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  82028. "use strict";
  82029. var BABYLON;
  82030. (function (BABYLON) {
  82031. /**
  82032. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  82033. * Screen rotation is taken into account.
  82034. */
  82035. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  82036. function FreeCameraDeviceOrientationInput() {
  82037. var _this = this;
  82038. this._screenOrientationAngle = 0;
  82039. this._screenQuaternion = new BABYLON.Quaternion();
  82040. this._alpha = 0;
  82041. this._beta = 0;
  82042. this._gamma = 0;
  82043. this._orientationChanged = function () {
  82044. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  82045. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  82046. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  82047. };
  82048. this._deviceOrientation = function (evt) {
  82049. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  82050. _this._beta = evt.beta !== null ? evt.beta : 0;
  82051. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  82052. };
  82053. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  82054. this._orientationChanged();
  82055. }
  82056. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  82057. get: function () {
  82058. return this._camera;
  82059. },
  82060. set: function (camera) {
  82061. this._camera = camera;
  82062. if (this._camera != null && !this._camera.rotationQuaternion) {
  82063. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  82064. }
  82065. },
  82066. enumerable: true,
  82067. configurable: true
  82068. });
  82069. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  82070. window.addEventListener("orientationchange", this._orientationChanged);
  82071. window.addEventListener("deviceorientation", this._deviceOrientation);
  82072. //In certain cases, the attach control is called AFTER orientation was changed,
  82073. //So this is needed.
  82074. this._orientationChanged();
  82075. };
  82076. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  82077. window.removeEventListener("orientationchange", this._orientationChanged);
  82078. window.removeEventListener("deviceorientation", this._deviceOrientation);
  82079. };
  82080. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  82081. //if no device orientation provided, don't update the rotation.
  82082. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  82083. if (!this._alpha)
  82084. return;
  82085. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  82086. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  82087. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  82088. //Mirror on XY Plane
  82089. this._camera.rotationQuaternion.z *= -1;
  82090. this._camera.rotationQuaternion.w *= -1;
  82091. };
  82092. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  82093. return "FreeCameraDeviceOrientationInput";
  82094. };
  82095. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  82096. return "deviceOrientation";
  82097. };
  82098. return FreeCameraDeviceOrientationInput;
  82099. }());
  82100. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  82101. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  82102. })(BABYLON || (BABYLON = {}));
  82103. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  82104. "use strict";
  82105. var BABYLON;
  82106. (function (BABYLON) {
  82107. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  82108. function ArcRotateCameraVRDeviceOrientationInput() {
  82109. this.alphaCorrection = 1;
  82110. this.betaCorrection = 1;
  82111. this.gammaCorrection = 1;
  82112. this._alpha = 0;
  82113. this._gamma = 0;
  82114. this._dirty = false;
  82115. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  82116. }
  82117. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  82118. this.camera.attachControl(element, noPreventDefault);
  82119. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  82120. };
  82121. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  82122. if (evt.alpha !== null) {
  82123. this._alpha = +evt.alpha | 0;
  82124. }
  82125. if (evt.gamma !== null) {
  82126. this._gamma = +evt.gamma | 0;
  82127. }
  82128. this._dirty = true;
  82129. };
  82130. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  82131. if (this._dirty) {
  82132. this._dirty = false;
  82133. if (this._gamma < 0) {
  82134. this._gamma = 180 + this._gamma;
  82135. }
  82136. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  82137. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  82138. }
  82139. };
  82140. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  82141. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  82142. };
  82143. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  82144. return "ArcRotateCameraVRDeviceOrientationInput";
  82145. };
  82146. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  82147. return "VRDeviceOrientation";
  82148. };
  82149. return ArcRotateCameraVRDeviceOrientationInput;
  82150. }());
  82151. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  82152. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  82153. })(BABYLON || (BABYLON = {}));
  82154. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  82155. "use strict";
  82156. var BABYLON;
  82157. (function (BABYLON) {
  82158. var VRCameraMetrics = /** @class */ (function () {
  82159. function VRCameraMetrics() {
  82160. this.compensateDistortion = true;
  82161. }
  82162. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  82163. get: function () {
  82164. return this.hResolution / (2 * this.vResolution);
  82165. },
  82166. enumerable: true,
  82167. configurable: true
  82168. });
  82169. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  82170. get: function () {
  82171. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  82172. },
  82173. enumerable: true,
  82174. configurable: true
  82175. });
  82176. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  82177. get: function () {
  82178. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82179. var h = (4 * meters) / this.hScreenSize;
  82180. return BABYLON.Matrix.Translation(h, 0, 0);
  82181. },
  82182. enumerable: true,
  82183. configurable: true
  82184. });
  82185. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  82186. get: function () {
  82187. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82188. var h = (4 * meters) / this.hScreenSize;
  82189. return BABYLON.Matrix.Translation(-h, 0, 0);
  82190. },
  82191. enumerable: true,
  82192. configurable: true
  82193. });
  82194. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  82195. get: function () {
  82196. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  82197. },
  82198. enumerable: true,
  82199. configurable: true
  82200. });
  82201. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  82202. get: function () {
  82203. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  82204. },
  82205. enumerable: true,
  82206. configurable: true
  82207. });
  82208. VRCameraMetrics.GetDefault = function () {
  82209. var result = new VRCameraMetrics();
  82210. result.hResolution = 1280;
  82211. result.vResolution = 800;
  82212. result.hScreenSize = 0.149759993;
  82213. result.vScreenSize = 0.0935999975;
  82214. result.vScreenCenter = 0.0467999987;
  82215. result.eyeToScreenDistance = 0.0410000011;
  82216. result.lensSeparationDistance = 0.0635000020;
  82217. result.interpupillaryDistance = 0.0640000030;
  82218. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  82219. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  82220. result.postProcessScaleFactor = 1.714605507808412;
  82221. result.lensCenterOffset = 0.151976421;
  82222. return result;
  82223. };
  82224. return VRCameraMetrics;
  82225. }());
  82226. BABYLON.VRCameraMetrics = VRCameraMetrics;
  82227. })(BABYLON || (BABYLON = {}));
  82228. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  82229. "use strict";
  82230. var BABYLON;
  82231. (function (BABYLON) {
  82232. /**
  82233. * This represents a WebVR camera.
  82234. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  82235. * @example http://doc.babylonjs.com/how_to/webvr_camera
  82236. */
  82237. var WebVRFreeCamera = /** @class */ (function (_super) {
  82238. __extends(WebVRFreeCamera, _super);
  82239. /**
  82240. * Instantiates a WebVRFreeCamera.
  82241. * @param name The name of the WebVRFreeCamera
  82242. * @param position The starting anchor position for the camera
  82243. * @param scene The scene the camera belongs to
  82244. * @param webVROptions a set of customizable options for the webVRCamera
  82245. */
  82246. function WebVRFreeCamera(name, position, scene, webVROptions) {
  82247. if (webVROptions === void 0) { webVROptions = {}; }
  82248. var _this = _super.call(this, name, position, scene) || this;
  82249. _this.webVROptions = webVROptions;
  82250. /**
  82251. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  82252. */
  82253. _this._vrDevice = null;
  82254. /**
  82255. * The rawPose of the vrDevice.
  82256. */
  82257. _this.rawPose = null;
  82258. _this._specsVersion = "1.1";
  82259. _this._attached = false;
  82260. _this._descendants = [];
  82261. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82262. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82263. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  82264. _this._standingMatrix = null;
  82265. /**
  82266. * Represents device position in babylon space.
  82267. */
  82268. _this.devicePosition = BABYLON.Vector3.Zero();
  82269. /**
  82270. * Represents device rotation in babylon space.
  82271. */
  82272. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  82273. /**
  82274. * The scale of the device to be used when translating from device space to babylon space.
  82275. */
  82276. _this.deviceScaleFactor = 1;
  82277. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82278. _this._worldToDevice = BABYLON.Matrix.Identity();
  82279. /**
  82280. * References to the webVR controllers for the vrDevice.
  82281. */
  82282. _this.controllers = [];
  82283. /**
  82284. * Emits an event when a controller is attached.
  82285. */
  82286. _this.onControllersAttachedObservable = new BABYLON.Observable();
  82287. /**
  82288. * Emits an event when a controller's mesh has been loaded;
  82289. */
  82290. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82291. /**
  82292. * If the rig cameras be used as parent instead of this camera.
  82293. */
  82294. _this.rigParenting = true;
  82295. _this._defaultHeight = undefined;
  82296. _this._workingVector = BABYLON.Vector3.Zero();
  82297. _this._oneVector = BABYLON.Vector3.One();
  82298. _this._workingMatrix = BABYLON.Matrix.Identity();
  82299. _this._cache.position = BABYLON.Vector3.Zero();
  82300. if (webVROptions.defaultHeight) {
  82301. _this._defaultHeight = webVROptions.defaultHeight;
  82302. _this.position.y = _this._defaultHeight;
  82303. }
  82304. _this.minZ = 0.1;
  82305. //legacy support - the compensation boolean was removed.
  82306. if (arguments.length === 5) {
  82307. _this.webVROptions = arguments[4];
  82308. }
  82309. // default webVR options
  82310. if (_this.webVROptions.trackPosition == undefined) {
  82311. _this.webVROptions.trackPosition = true;
  82312. }
  82313. if (_this.webVROptions.controllerMeshes == undefined) {
  82314. _this.webVROptions.controllerMeshes = true;
  82315. }
  82316. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  82317. _this.webVROptions.defaultLightingOnControllers = true;
  82318. }
  82319. _this.rotationQuaternion = new BABYLON.Quaternion();
  82320. if (_this.webVROptions && _this.webVROptions.positionScale) {
  82321. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  82322. }
  82323. //enable VR
  82324. var engine = _this.getEngine();
  82325. _this._onVREnabled = function (success) { if (success) {
  82326. _this.initControllers();
  82327. } };
  82328. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  82329. engine.initWebVR().add(function (event) {
  82330. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  82331. return;
  82332. }
  82333. _this._vrDevice = event.vrDisplay;
  82334. //reset the rig parameters.
  82335. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  82336. if (_this._attached) {
  82337. _this.getEngine().enableVR();
  82338. }
  82339. });
  82340. if (typeof (VRFrameData) !== "undefined")
  82341. _this._frameData = new VRFrameData();
  82342. /**
  82343. * The idea behind the following lines:
  82344. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82345. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82346. * the second will not show it correctly.
  82347. *
  82348. * To solve this - each object that has the camera as parent will be added to a protected array.
  82349. * When the rig camera renders, it will take this array and set all of those to be its children.
  82350. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82351. * Amazing!
  82352. */
  82353. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82354. if (camera.parent === _this && _this.rigParenting) {
  82355. _this._descendants = _this.getDescendants(true, function (n) {
  82356. // don't take the cameras or the controllers!
  82357. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82358. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82359. return !isController && !isRigCamera;
  82360. });
  82361. _this._descendants.forEach(function (node) {
  82362. node.parent = camera;
  82363. });
  82364. }
  82365. });
  82366. scene.onAfterCameraRenderObservable.add(function (camera) {
  82367. if (camera.parent === _this && _this.rigParenting) {
  82368. _this._descendants.forEach(function (node) {
  82369. node.parent = _this;
  82370. });
  82371. }
  82372. });
  82373. return _this;
  82374. }
  82375. /**
  82376. * Gets the device distance from the ground in meters.
  82377. * @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.
  82378. */
  82379. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82380. if (this._standingMatrix) {
  82381. // Add standing matrix offset to get real offset from ground in room
  82382. this._standingMatrix.getTranslationToRef(this._workingVector);
  82383. return this._deviceRoomPosition.y + this._workingVector.y;
  82384. }
  82385. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82386. return this._defaultHeight || 0;
  82387. };
  82388. /**
  82389. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82390. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82391. */
  82392. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82393. var _this = this;
  82394. if (callback === void 0) { callback = function (bool) { }; }
  82395. // Use standing matrix if available
  82396. this.getEngine().initWebVRAsync().then(function (result) {
  82397. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82398. callback(false);
  82399. }
  82400. else {
  82401. _this._standingMatrix = new BABYLON.Matrix();
  82402. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82403. if (!_this.getScene().useRightHandedSystem) {
  82404. [2, 6, 8, 9, 14].forEach(function (num) {
  82405. if (_this._standingMatrix) {
  82406. _this._standingMatrix.m[num] *= -1;
  82407. }
  82408. });
  82409. }
  82410. callback(true);
  82411. }
  82412. });
  82413. };
  82414. /**
  82415. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82416. * @returns A promise with a boolean set to if the standing matrix is supported.
  82417. */
  82418. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82419. var _this = this;
  82420. return new Promise(function (res, rej) {
  82421. _this.useStandingMatrix(function (supported) {
  82422. res(supported);
  82423. });
  82424. });
  82425. };
  82426. /**
  82427. * Disposes the camera
  82428. */
  82429. WebVRFreeCamera.prototype.dispose = function () {
  82430. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82431. _super.prototype.dispose.call(this);
  82432. };
  82433. /**
  82434. * Gets a vrController by name.
  82435. * @param name The name of the controller to retreive
  82436. * @returns the controller matching the name specified or null if not found
  82437. */
  82438. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82439. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82440. var gp = _a[_i];
  82441. if (gp.hand === name) {
  82442. return gp;
  82443. }
  82444. }
  82445. return null;
  82446. };
  82447. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82448. /**
  82449. * The controller corrisponding to the users left hand.
  82450. */
  82451. get: function () {
  82452. if (!this._leftController) {
  82453. this._leftController = this.getControllerByName("left");
  82454. }
  82455. return this._leftController;
  82456. },
  82457. enumerable: true,
  82458. configurable: true
  82459. });
  82460. ;
  82461. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82462. /**
  82463. * The controller corrisponding to the users right hand.
  82464. */
  82465. get: function () {
  82466. if (!this._rightController) {
  82467. this._rightController = this.getControllerByName("right");
  82468. }
  82469. return this._rightController;
  82470. },
  82471. enumerable: true,
  82472. configurable: true
  82473. });
  82474. ;
  82475. /**
  82476. * Casts a ray forward from the vrCamera's gaze.
  82477. * @param length Length of the ray (default: 100)
  82478. * @returns the ray corrisponding to the gaze
  82479. */
  82480. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82481. if (length === void 0) { length = 100; }
  82482. if (this.leftCamera) {
  82483. // Use left eye to avoid computation to compute center on every call
  82484. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82485. }
  82486. else {
  82487. return _super.prototype.getForwardRay.call(this, length);
  82488. }
  82489. };
  82490. /**
  82491. * Updates the camera based on device's frame data
  82492. */
  82493. WebVRFreeCamera.prototype._checkInputs = function () {
  82494. if (this._vrDevice && this._vrDevice.isPresenting) {
  82495. this._vrDevice.getFrameData(this._frameData);
  82496. this.updateFromDevice(this._frameData.pose);
  82497. }
  82498. _super.prototype._checkInputs.call(this);
  82499. };
  82500. /**
  82501. * Updates the poseControlled values based on the input device pose.
  82502. * @param poseData Pose coming from the device
  82503. */
  82504. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82505. if (poseData && poseData.orientation) {
  82506. this.rawPose = poseData;
  82507. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82508. if (this.getScene().useRightHandedSystem) {
  82509. this._deviceRoomRotationQuaternion.z *= -1;
  82510. this._deviceRoomRotationQuaternion.w *= -1;
  82511. }
  82512. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82513. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82514. if (this.getScene().useRightHandedSystem) {
  82515. this._deviceRoomPosition.z *= -1;
  82516. }
  82517. }
  82518. }
  82519. };
  82520. /**
  82521. * WebVR's attach control will start broadcasting frames to the device.
  82522. * Note that in certain browsers (chrome for example) this function must be called
  82523. * within a user-interaction callback. Example:
  82524. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82525. *
  82526. * @param element html element to attach the vrDevice to
  82527. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82528. */
  82529. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82530. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82531. this._attached = true;
  82532. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82533. if (this._vrDevice) {
  82534. this.getEngine().enableVR();
  82535. }
  82536. };
  82537. /**
  82538. * Detaches the camera from the html element and disables VR
  82539. *
  82540. * @param element html element to detach from
  82541. */
  82542. WebVRFreeCamera.prototype.detachControl = function (element) {
  82543. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82544. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82545. _super.prototype.detachControl.call(this, element);
  82546. this._attached = false;
  82547. this.getEngine().disableVR();
  82548. };
  82549. /**
  82550. * @returns the name of this class
  82551. */
  82552. WebVRFreeCamera.prototype.getClassName = function () {
  82553. return "WebVRFreeCamera";
  82554. };
  82555. /**
  82556. * Calls resetPose on the vrDisplay
  82557. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82558. */
  82559. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82560. //uses the vrDisplay's "resetPose()".
  82561. //pitch and roll won't be affected.
  82562. this._vrDevice.resetPose();
  82563. };
  82564. /**
  82565. * Updates the rig cameras (left and right eye)
  82566. */
  82567. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82568. var camLeft = this._rigCameras[0];
  82569. var camRight = this._rigCameras[1];
  82570. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82571. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82572. camLeft.position.copyFrom(this._deviceRoomPosition);
  82573. camRight.position.copyFrom(this._deviceRoomPosition);
  82574. };
  82575. /**
  82576. * Updates the cached values of the camera
  82577. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82578. */
  82579. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82580. var _this = this;
  82581. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82582. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82583. if (!this.updateCacheCalled) {
  82584. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82585. this.updateCacheCalled = true;
  82586. this.update();
  82587. }
  82588. // Set working vector to the device position in room space rotated by the new rotation
  82589. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82590. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82591. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82592. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82593. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82594. // Add translation from anchor position
  82595. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82596. this._workingVector.addInPlace(this.position);
  82597. this._workingVector.subtractInPlace(this._cache.position);
  82598. this._deviceToWorld.setTranslation(this._workingVector);
  82599. // Set an inverted matrix to be used when updating the camera
  82600. this._deviceToWorld.invertToRef(this._worldToDevice);
  82601. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82602. this.controllers.forEach(function (controller) {
  82603. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82604. controller.update();
  82605. });
  82606. }
  82607. if (!ignoreParentClass) {
  82608. _super.prototype._updateCache.call(this);
  82609. }
  82610. this.updateCacheCalled = false;
  82611. };
  82612. /**
  82613. * Updates the current device position and rotation in the babylon world
  82614. */
  82615. WebVRFreeCamera.prototype.update = function () {
  82616. // Get current device position in babylon world
  82617. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82618. // Get current device rotation in babylon world
  82619. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82620. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82621. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82622. _super.prototype.update.call(this);
  82623. };
  82624. /**
  82625. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82626. * @returns an identity matrix
  82627. */
  82628. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82629. return BABYLON.Matrix.Identity();
  82630. };
  82631. /**
  82632. * This function is called by the two RIG cameras.
  82633. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82634. */
  82635. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82636. var _this = this;
  82637. // Update the parent camera prior to using a child camera to avoid desynchronization
  82638. var parentCamera = this._cameraRigParams["parentCamera"];
  82639. parentCamera._updateCache();
  82640. //WebVR 1.1
  82641. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82642. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82643. if (!this.getScene().useRightHandedSystem) {
  82644. [2, 6, 8, 9, 14].forEach(function (num) {
  82645. _this._webvrViewMatrix.m[num] *= -1;
  82646. });
  82647. }
  82648. // update the camera rotation matrix
  82649. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82650. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82651. // Computing target and final matrix
  82652. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82653. // should the view matrix be updated with scale and position offset?
  82654. if (parentCamera.deviceScaleFactor !== 1) {
  82655. this._webvrViewMatrix.invert();
  82656. // scale the position, if set
  82657. if (parentCamera.deviceScaleFactor) {
  82658. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82659. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82660. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82661. }
  82662. this._webvrViewMatrix.invert();
  82663. }
  82664. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82665. return this._webvrViewMatrix;
  82666. };
  82667. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82668. var _this = this;
  82669. var parentCamera = this.parent;
  82670. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82671. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82672. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82673. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82674. //babylon compatible matrix
  82675. if (!this.getScene().useRightHandedSystem) {
  82676. [8, 9, 10, 11].forEach(function (num) {
  82677. _this._projectionMatrix.m[num] *= -1;
  82678. });
  82679. }
  82680. return this._projectionMatrix;
  82681. };
  82682. /**
  82683. * Initializes the controllers and their meshes
  82684. */
  82685. WebVRFreeCamera.prototype.initControllers = function () {
  82686. var _this = this;
  82687. this.controllers = [];
  82688. var manager = this.getScene().gamepadManager;
  82689. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82690. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82691. var webVrController = gamepad;
  82692. if (webVrController.defaultModel) {
  82693. webVrController.defaultModel.setEnabled(false);
  82694. }
  82695. if (webVrController.hand === "right") {
  82696. _this._rightController = null;
  82697. }
  82698. if (webVrController.hand === "left") {
  82699. _this._leftController = null;
  82700. }
  82701. var controllerIndex = _this.controllers.indexOf(webVrController);
  82702. if (controllerIndex !== -1) {
  82703. _this.controllers.splice(controllerIndex, 1);
  82704. }
  82705. }
  82706. });
  82707. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82708. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82709. var webVrController_1 = gamepad;
  82710. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82711. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82712. if (_this.webVROptions.controllerMeshes) {
  82713. if (webVrController_1.defaultModel) {
  82714. webVrController_1.defaultModel.setEnabled(true);
  82715. }
  82716. else {
  82717. // Load the meshes
  82718. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82719. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82720. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82721. if (_this.webVROptions.defaultLightingOnControllers) {
  82722. if (!_this._lightOnControllers) {
  82723. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82724. }
  82725. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82726. var children = mesh.getChildren();
  82727. if (children.length !== 0) {
  82728. children.forEach(function (mesh) {
  82729. light.includedOnlyMeshes.push(mesh);
  82730. activateLightOnSubMeshes_1(mesh, light);
  82731. });
  82732. }
  82733. };
  82734. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82735. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82736. }
  82737. });
  82738. }
  82739. }
  82740. webVrController_1.attachToPoseControlledCamera(_this);
  82741. // since this is async - sanity check. Is the controller already stored?
  82742. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82743. //add to the controllers array
  82744. _this.controllers.push(webVrController_1);
  82745. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82746. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82747. // So we're overriding setting left & right manually to be sure
  82748. var firstViveWandDetected = false;
  82749. for (var i = 0; i < _this.controllers.length; i++) {
  82750. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82751. if (!firstViveWandDetected) {
  82752. firstViveWandDetected = true;
  82753. _this.controllers[i].hand = "left";
  82754. }
  82755. else {
  82756. _this.controllers[i].hand = "right";
  82757. }
  82758. }
  82759. }
  82760. //did we find enough controllers? Great! let the developer know.
  82761. if (_this.controllers.length >= 2) {
  82762. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82763. }
  82764. }
  82765. }
  82766. });
  82767. };
  82768. return WebVRFreeCamera;
  82769. }(BABYLON.FreeCamera));
  82770. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82771. })(BABYLON || (BABYLON = {}));
  82772. //# sourceMappingURL=babylon.webVRCamera.js.map
  82773. "use strict";
  82774. var BABYLON;
  82775. (function (BABYLON) {
  82776. // We're mainly based on the logic defined into the FreeCamera code
  82777. /**
  82778. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82779. * being tilted forward or back and left or right.
  82780. */
  82781. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82782. __extends(DeviceOrientationCamera, _super);
  82783. /**
  82784. * Creates a new device orientation camera
  82785. * @param name The name of the camera
  82786. * @param position The start position camera
  82787. * @param scene The scene the camera belongs to
  82788. */
  82789. function DeviceOrientationCamera(name, position, scene) {
  82790. var _this = _super.call(this, name, position, scene) || this;
  82791. _this._quaternionCache = new BABYLON.Quaternion();
  82792. _this.inputs.addDeviceOrientation();
  82793. return _this;
  82794. }
  82795. /**
  82796. * Gets the current instance class name ("DeviceOrientationCamera").
  82797. * This helps avoiding instanceof at run time.
  82798. * @returns the class name
  82799. */
  82800. DeviceOrientationCamera.prototype.getClassName = function () {
  82801. return "DeviceOrientationCamera";
  82802. };
  82803. /**
  82804. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82805. */
  82806. DeviceOrientationCamera.prototype._checkInputs = function () {
  82807. _super.prototype._checkInputs.call(this);
  82808. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82809. if (this._initialQuaternion) {
  82810. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82811. }
  82812. };
  82813. /**
  82814. * Reset the camera to its default orientation on the specified axis only.
  82815. * @param axis The axis to reset
  82816. */
  82817. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82818. var _this = this;
  82819. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82820. //can only work if this camera has a rotation quaternion already.
  82821. if (!this.rotationQuaternion)
  82822. return;
  82823. if (!this._initialQuaternion) {
  82824. this._initialQuaternion = new BABYLON.Quaternion();
  82825. }
  82826. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82827. ['x', 'y', 'z'].forEach(function (axisName) {
  82828. if (!axis[axisName]) {
  82829. _this._initialQuaternion[axisName] = 0;
  82830. }
  82831. else {
  82832. _this._initialQuaternion[axisName] *= -1;
  82833. }
  82834. });
  82835. this._initialQuaternion.normalize();
  82836. //force rotation update
  82837. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82838. };
  82839. return DeviceOrientationCamera;
  82840. }(BABYLON.FreeCamera));
  82841. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82842. })(BABYLON || (BABYLON = {}));
  82843. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82844. "use strict";
  82845. var BABYLON;
  82846. (function (BABYLON) {
  82847. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82848. __extends(VRDeviceOrientationFreeCamera, _super);
  82849. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82850. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82851. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82852. var _this = _super.call(this, name, position, scene) || this;
  82853. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82854. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82855. return _this;
  82856. }
  82857. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82858. return "VRDeviceOrientationFreeCamera";
  82859. };
  82860. return VRDeviceOrientationFreeCamera;
  82861. }(BABYLON.DeviceOrientationCamera));
  82862. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82863. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82864. __extends(VRDeviceOrientationGamepadCamera, _super);
  82865. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82866. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82867. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82868. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82869. _this.inputs.addGamepad();
  82870. return _this;
  82871. }
  82872. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82873. return "VRDeviceOrientationGamepadCamera";
  82874. };
  82875. return VRDeviceOrientationGamepadCamera;
  82876. }(VRDeviceOrientationFreeCamera));
  82877. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82878. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82879. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82880. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82881. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82882. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82883. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82884. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82885. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82886. _this.inputs.addVRDeviceOrientation();
  82887. return _this;
  82888. }
  82889. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82890. return "VRDeviceOrientationArcRotateCamera";
  82891. };
  82892. return VRDeviceOrientationArcRotateCamera;
  82893. }(BABYLON.ArcRotateCamera));
  82894. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82895. })(BABYLON || (BABYLON = {}));
  82896. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82897. "use strict";
  82898. var BABYLON;
  82899. (function (BABYLON) {
  82900. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82901. __extends(AnaglyphFreeCamera, _super);
  82902. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82903. var _this = _super.call(this, name, position, scene) || this;
  82904. _this.interaxialDistance = interaxialDistance;
  82905. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82906. return _this;
  82907. }
  82908. AnaglyphFreeCamera.prototype.getClassName = function () {
  82909. return "AnaglyphFreeCamera";
  82910. };
  82911. return AnaglyphFreeCamera;
  82912. }(BABYLON.FreeCamera));
  82913. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82914. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82915. __extends(AnaglyphArcRotateCamera, _super);
  82916. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82917. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82918. _this.interaxialDistance = interaxialDistance;
  82919. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82920. return _this;
  82921. }
  82922. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82923. return "AnaglyphArcRotateCamera";
  82924. };
  82925. return AnaglyphArcRotateCamera;
  82926. }(BABYLON.ArcRotateCamera));
  82927. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82928. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82929. __extends(AnaglyphGamepadCamera, _super);
  82930. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82931. var _this = _super.call(this, name, position, scene) || this;
  82932. _this.interaxialDistance = interaxialDistance;
  82933. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82934. return _this;
  82935. }
  82936. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82937. return "AnaglyphGamepadCamera";
  82938. };
  82939. return AnaglyphGamepadCamera;
  82940. }(BABYLON.GamepadCamera));
  82941. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82942. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82943. __extends(AnaglyphUniversalCamera, _super);
  82944. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82945. var _this = _super.call(this, name, position, scene) || this;
  82946. _this.interaxialDistance = interaxialDistance;
  82947. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82948. return _this;
  82949. }
  82950. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82951. return "AnaglyphUniversalCamera";
  82952. };
  82953. return AnaglyphUniversalCamera;
  82954. }(BABYLON.UniversalCamera));
  82955. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82956. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82957. __extends(StereoscopicFreeCamera, _super);
  82958. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82959. var _this = _super.call(this, name, position, scene) || this;
  82960. _this.interaxialDistance = interaxialDistance;
  82961. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82962. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82963. return _this;
  82964. }
  82965. StereoscopicFreeCamera.prototype.getClassName = function () {
  82966. return "StereoscopicFreeCamera";
  82967. };
  82968. return StereoscopicFreeCamera;
  82969. }(BABYLON.FreeCamera));
  82970. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82971. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82972. __extends(StereoscopicArcRotateCamera, _super);
  82973. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82974. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82975. _this.interaxialDistance = interaxialDistance;
  82976. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82977. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82978. return _this;
  82979. }
  82980. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82981. return "StereoscopicArcRotateCamera";
  82982. };
  82983. return StereoscopicArcRotateCamera;
  82984. }(BABYLON.ArcRotateCamera));
  82985. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82986. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82987. __extends(StereoscopicGamepadCamera, _super);
  82988. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82989. var _this = _super.call(this, name, position, scene) || this;
  82990. _this.interaxialDistance = interaxialDistance;
  82991. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82992. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82993. return _this;
  82994. }
  82995. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82996. return "StereoscopicGamepadCamera";
  82997. };
  82998. return StereoscopicGamepadCamera;
  82999. }(BABYLON.GamepadCamera));
  83000. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  83001. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  83002. __extends(StereoscopicUniversalCamera, _super);
  83003. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  83004. var _this = _super.call(this, name, position, scene) || this;
  83005. _this.interaxialDistance = interaxialDistance;
  83006. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  83007. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  83008. return _this;
  83009. }
  83010. StereoscopicUniversalCamera.prototype.getClassName = function () {
  83011. return "StereoscopicUniversalCamera";
  83012. };
  83013. return StereoscopicUniversalCamera;
  83014. }(BABYLON.UniversalCamera));
  83015. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  83016. })(BABYLON || (BABYLON = {}));
  83017. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  83018. "use strict";
  83019. var BABYLON;
  83020. (function (BABYLON) {
  83021. var VRExperienceHelperGazer = /** @class */ (function () {
  83022. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  83023. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  83024. this.scene = scene;
  83025. this._pointerDownOnMeshAsked = false;
  83026. this._isActionableMesh = false;
  83027. this._teleportationRequestInitiated = false;
  83028. this._teleportationBackRequestInitiated = false;
  83029. this._dpadPressed = true;
  83030. this._activePointer = false;
  83031. this._id = VRExperienceHelperGazer._idCounter++;
  83032. // Gaze tracker
  83033. if (!gazeTrackerToClone) {
  83034. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  83035. this._gazeTracker.bakeCurrentTransformIntoVertices();
  83036. this._gazeTracker.isPickable = false;
  83037. this._gazeTracker.isVisible = false;
  83038. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  83039. targetMat.specularColor = BABYLON.Color3.Black();
  83040. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  83041. targetMat.backFaceCulling = false;
  83042. this._gazeTracker.material = targetMat;
  83043. }
  83044. else {
  83045. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  83046. }
  83047. }
  83048. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  83049. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  83050. };
  83051. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  83052. this._pointerDownOnMeshAsked = true;
  83053. if (this._currentMeshSelected && this._currentHit) {
  83054. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  83055. }
  83056. };
  83057. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  83058. if (this._currentMeshSelected && this._currentHit) {
  83059. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  83060. }
  83061. this._pointerDownOnMeshAsked = false;
  83062. };
  83063. VRExperienceHelperGazer.prototype._activatePointer = function () {
  83064. this._activePointer = true;
  83065. };
  83066. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  83067. this._activePointer = false;
  83068. };
  83069. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  83070. };
  83071. VRExperienceHelperGazer.prototype.dispose = function () {
  83072. this._interactionsEnabled = false;
  83073. this._teleportationEnabled = false;
  83074. };
  83075. VRExperienceHelperGazer._idCounter = 0;
  83076. return VRExperienceHelperGazer;
  83077. }());
  83078. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  83079. __extends(VRExperienceHelperControllerGazer, _super);
  83080. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  83081. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  83082. _this.webVRController = webVRController;
  83083. // Laser pointer
  83084. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  83085. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  83086. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  83087. laserPointerMaterial.alpha = 0.6;
  83088. _this._laserPointer.material = laserPointerMaterial;
  83089. _this._laserPointer.rotation.x = Math.PI / 2;
  83090. _this._laserPointer.position.z = -0.5;
  83091. _this._laserPointer.isVisible = false;
  83092. if (!webVRController.mesh) {
  83093. // Create an empty mesh that is used prior to loading the high quality model
  83094. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  83095. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  83096. preloadPointerPose.rotation.x = -0.7;
  83097. preloadMesh.addChild(preloadPointerPose);
  83098. webVRController.attachToMesh(preloadMesh);
  83099. }
  83100. _this._setLaserPointerParent(webVRController.mesh);
  83101. return _this;
  83102. }
  83103. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  83104. return this.webVRController.getForwardRay(length);
  83105. };
  83106. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  83107. _super.prototype._activatePointer.call(this);
  83108. this._laserPointer.isVisible = true;
  83109. };
  83110. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  83111. _super.prototype._deactivatePointer.call(this);
  83112. this._laserPointer.isVisible = false;
  83113. };
  83114. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  83115. this._laserPointer.material.emissiveColor = color;
  83116. };
  83117. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  83118. var makeNotPick = function (root) {
  83119. root.name += " laserPointer";
  83120. root.getChildMeshes().forEach(function (c) {
  83121. makeNotPick(c);
  83122. });
  83123. };
  83124. makeNotPick(mesh);
  83125. var childMeshes = mesh.getChildMeshes();
  83126. this.webVRController._pointingPoseNode = null;
  83127. for (var i = 0; i < childMeshes.length; i++) {
  83128. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  83129. mesh = childMeshes[i];
  83130. this.webVRController._pointingPoseNode = mesh;
  83131. break;
  83132. }
  83133. }
  83134. this._laserPointer.parent = mesh;
  83135. };
  83136. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  83137. this._laserPointer.scaling.y = distance;
  83138. this._laserPointer.position.z = -distance / 2;
  83139. };
  83140. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  83141. _super.prototype.dispose.call(this);
  83142. this._laserPointer.dispose();
  83143. };
  83144. return VRExperienceHelperControllerGazer;
  83145. }(VRExperienceHelperGazer));
  83146. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  83147. __extends(VRExperienceHelperCameraGazer, _super);
  83148. function VRExperienceHelperCameraGazer(getCamera, scene) {
  83149. var _this = _super.call(this, scene) || this;
  83150. _this.getCamera = getCamera;
  83151. return _this;
  83152. }
  83153. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  83154. var camera = this.getCamera();
  83155. if (camera) {
  83156. return camera.getForwardRay(length);
  83157. }
  83158. else {
  83159. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  83160. }
  83161. };
  83162. return VRExperienceHelperCameraGazer;
  83163. }(VRExperienceHelperGazer));
  83164. /**
  83165. * Helps to quickly add VR support to an existing scene.
  83166. * See http://doc.babylonjs.com/how_to/webvr_helper
  83167. */
  83168. var VRExperienceHelper = /** @class */ (function () {
  83169. /**
  83170. * Instantiates a VRExperienceHelper.
  83171. * Helps to quickly add VR support to an existing scene.
  83172. * @param scene The scene the VRExperienceHelper belongs to.
  83173. * @param webVROptions Options to modify the vr experience helper's behavior.
  83174. */
  83175. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  83176. if (webVROptions === void 0) { webVROptions = {}; }
  83177. var _this = this;
  83178. this.webVROptions = webVROptions;
  83179. // Can the system support WebVR, even if a headset isn't plugged in?
  83180. this._webVRsupported = false;
  83181. // If WebVR is supported, is a headset plugged in and are we ready to present?
  83182. this._webVRready = false;
  83183. // Are we waiting for the requestPresent callback to complete?
  83184. this._webVRrequesting = false;
  83185. // Are we presenting to the headset right now?
  83186. this._webVRpresenting = false;
  83187. // Are we presenting in the fullscreen fallback?
  83188. this._fullscreenVRpresenting = false;
  83189. /**
  83190. * Observable raised when entering VR.
  83191. */
  83192. this.onEnteringVRObservable = new BABYLON.Observable();
  83193. /**
  83194. * Observable raised when exiting VR.
  83195. */
  83196. this.onExitingVRObservable = new BABYLON.Observable();
  83197. /**
  83198. * Observable raised when controller mesh is loaded.
  83199. */
  83200. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  83201. this._useCustomVRButton = false;
  83202. this._teleportationRequested = false;
  83203. this._teleportActive = false;
  83204. this._floorMeshesCollection = [];
  83205. this._rotationAllowed = true;
  83206. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  83207. this._rotationRightAsked = false;
  83208. this._rotationLeftAsked = false;
  83209. this._isDefaultTeleportationTarget = true;
  83210. this._teleportationFillColor = "#444444";
  83211. this._teleportationBorderColor = "#FFFFFF";
  83212. this._rotationAngle = 0;
  83213. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  83214. this._padSensibilityUp = 0.65;
  83215. this._padSensibilityDown = 0.35;
  83216. this.leftController = null;
  83217. this.rightController = null;
  83218. /**
  83219. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  83220. */
  83221. this.onNewMeshSelected = new BABYLON.Observable();
  83222. /**
  83223. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  83224. */
  83225. this.onNewMeshPicked = new BABYLON.Observable();
  83226. /**
  83227. * Observable raised before camera teleportation
  83228. */
  83229. this.onBeforeCameraTeleport = new BABYLON.Observable();
  83230. /**
  83231. * Observable raised after camera teleportation
  83232. */
  83233. this.onAfterCameraTeleport = new BABYLON.Observable();
  83234. /**
  83235. * Observable raised when current selected mesh gets unselected
  83236. */
  83237. this.onSelectedMeshUnselected = new BABYLON.Observable();
  83238. /**
  83239. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  83240. */
  83241. this.teleportationEnabled = true;
  83242. this._teleportationInitialized = false;
  83243. this._interactionsEnabled = false;
  83244. this._interactionsRequested = false;
  83245. this._displayGaze = true;
  83246. this._displayLaserPointer = true;
  83247. this._onResize = function () {
  83248. _this.moveButtonToBottomRight();
  83249. if (_this._fullscreenVRpresenting && _this._webVRready) {
  83250. _this.exitVR();
  83251. }
  83252. };
  83253. this._onFullscreenChange = function () {
  83254. if (document.fullscreen !== undefined) {
  83255. _this._fullscreenVRpresenting = document.fullscreen;
  83256. }
  83257. else if (document.mozFullScreen !== undefined) {
  83258. _this._fullscreenVRpresenting = document.mozFullScreen;
  83259. }
  83260. else if (document.webkitIsFullScreen !== undefined) {
  83261. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  83262. }
  83263. else if (document.msIsFullScreen !== undefined) {
  83264. _this._fullscreenVRpresenting = document.msIsFullScreen;
  83265. }
  83266. if (!_this._fullscreenVRpresenting && _this._canvas) {
  83267. _this.exitVR();
  83268. if (!_this._useCustomVRButton) {
  83269. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  83270. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  83271. }
  83272. }
  83273. };
  83274. this.beforeRender = function () {
  83275. if (_this.leftController && _this.leftController._activePointer) {
  83276. _this._castRayAndSelectObject(_this.leftController);
  83277. }
  83278. if (_this.rightController && _this.rightController._activePointer) {
  83279. _this._castRayAndSelectObject(_this.rightController);
  83280. }
  83281. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  83282. _this._castRayAndSelectObject(_this._cameraGazer);
  83283. }
  83284. else {
  83285. _this._cameraGazer._gazeTracker.isVisible = false;
  83286. }
  83287. };
  83288. this._onNewGamepadConnected = function (gamepad) {
  83289. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  83290. if (gamepad.leftStick) {
  83291. gamepad.onleftstickchanged(function (stickValues) {
  83292. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  83293. // Listening to classic/xbox gamepad only if no VR controller is active
  83294. if ((!_this.leftController && !_this.rightController) ||
  83295. ((_this.leftController && !_this.leftController._activePointer) &&
  83296. (_this.rightController && !_this.rightController._activePointer))) {
  83297. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  83298. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  83299. }
  83300. }
  83301. });
  83302. }
  83303. if (gamepad.rightStick) {
  83304. gamepad.onrightstickchanged(function (stickValues) {
  83305. if (_this._teleportationInitialized) {
  83306. _this._checkRotate(stickValues, _this._cameraGazer);
  83307. }
  83308. });
  83309. }
  83310. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  83311. gamepad.onbuttondown(function (buttonPressed) {
  83312. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83313. _this._cameraGazer._selectionPointerDown();
  83314. }
  83315. });
  83316. gamepad.onbuttonup(function (buttonPressed) {
  83317. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83318. _this._cameraGazer._selectionPointerUp();
  83319. }
  83320. });
  83321. }
  83322. }
  83323. else {
  83324. var webVRController = gamepad;
  83325. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  83326. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  83327. _this.rightController = controller;
  83328. }
  83329. else {
  83330. _this.leftController = controller;
  83331. }
  83332. _this._tryEnableInteractionOnController(controller);
  83333. }
  83334. };
  83335. // 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
  83336. this._tryEnableInteractionOnController = function (controller) {
  83337. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  83338. _this._enableInteractionOnController(controller);
  83339. }
  83340. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  83341. _this._enableTeleportationOnController(controller);
  83342. }
  83343. };
  83344. this._onNewGamepadDisconnected = function (gamepad) {
  83345. if (gamepad instanceof BABYLON.WebVRController) {
  83346. if (gamepad.hand === "left" && _this.leftController != null) {
  83347. _this.leftController.dispose();
  83348. _this.leftController = null;
  83349. }
  83350. if (gamepad.hand === "right" && _this.rightController != null) {
  83351. _this.rightController.dispose();
  83352. _this.rightController = null;
  83353. }
  83354. }
  83355. };
  83356. this._workingVector = BABYLON.Vector3.Zero();
  83357. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83358. this._workingMatrix = BABYLON.Matrix.Identity();
  83359. this._scene = scene;
  83360. this._canvas = scene.getEngine().getRenderingCanvas();
  83361. // Parse options
  83362. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83363. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83364. }
  83365. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83366. webVROptions.createDeviceOrientationCamera = true;
  83367. }
  83368. if (webVROptions.defaultHeight === undefined) {
  83369. webVROptions.defaultHeight = 1.7;
  83370. }
  83371. if (webVROptions.useCustomVRButton) {
  83372. this._useCustomVRButton = true;
  83373. if (webVROptions.customVRButton) {
  83374. this._btnVR = webVROptions.customVRButton;
  83375. }
  83376. }
  83377. if (webVROptions.rayLength) {
  83378. this._rayLength = webVROptions.rayLength;
  83379. }
  83380. this._defaultHeight = webVROptions.defaultHeight;
  83381. if (webVROptions.positionScale) {
  83382. this._rayLength *= webVROptions.positionScale;
  83383. this._defaultHeight *= webVROptions.positionScale;
  83384. }
  83385. // Set position
  83386. if (this._scene.activeCamera) {
  83387. this._position = this._scene.activeCamera.position.clone();
  83388. }
  83389. else {
  83390. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83391. }
  83392. // Set non-vr camera
  83393. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83394. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83395. // Copy data from existing camera
  83396. if (this._scene.activeCamera) {
  83397. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83398. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83399. // Set rotation from previous camera
  83400. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83401. var targetCamera = this._scene.activeCamera;
  83402. if (targetCamera.rotationQuaternion) {
  83403. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83404. }
  83405. else {
  83406. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83407. }
  83408. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83409. }
  83410. }
  83411. this._scene.activeCamera = this._deviceOrientationCamera;
  83412. if (this._canvas) {
  83413. this._scene.activeCamera.attachControl(this._canvas);
  83414. }
  83415. }
  83416. else {
  83417. this._existingCamera = this._scene.activeCamera;
  83418. }
  83419. // Create VR cameras
  83420. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83421. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83422. }
  83423. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83424. this._webVRCamera.useStandingMatrix();
  83425. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83426. // Create default button
  83427. if (!this._useCustomVRButton) {
  83428. this._btnVR = document.createElement("BUTTON");
  83429. this._btnVR.className = "babylonVRicon";
  83430. this._btnVR.id = "babylonVRiconbtn";
  83431. this._btnVR.title = "Click to switch to VR";
  83432. 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) }";
  83433. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83434. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83435. // css += ".babylonVRicon.vrdisplaysupported { }";
  83436. // css += ".babylonVRicon.vrdisplayready { }";
  83437. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83438. var style = document.createElement('style');
  83439. style.appendChild(document.createTextNode(css));
  83440. document.getElementsByTagName('head')[0].appendChild(style);
  83441. this.moveButtonToBottomRight();
  83442. }
  83443. // VR button click event
  83444. if (this._btnVR) {
  83445. this._btnVR.addEventListener("click", function () {
  83446. if (!_this.isInVRMode) {
  83447. _this.enterVR();
  83448. }
  83449. else {
  83450. _this.exitVR();
  83451. }
  83452. });
  83453. }
  83454. // Window events
  83455. window.addEventListener("resize", this._onResize);
  83456. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83457. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83458. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83459. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83460. // Display vr button when headset is connected
  83461. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83462. this.displayVRButton();
  83463. }
  83464. else {
  83465. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83466. if (e.vrDisplay) {
  83467. _this.displayVRButton();
  83468. }
  83469. });
  83470. }
  83471. // Exiting VR mode using 'ESC' key on desktop
  83472. this._onKeyDown = function (event) {
  83473. if (event.keyCode === 27 && _this.isInVRMode) {
  83474. _this.exitVR();
  83475. }
  83476. };
  83477. document.addEventListener("keydown", this._onKeyDown);
  83478. // Exiting VR mode double tapping the touch screen
  83479. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83480. if (_this.isInVRMode) {
  83481. _this.exitVR();
  83482. if (_this._fullscreenVRpresenting) {
  83483. _this._scene.getEngine().switchFullscreen(true);
  83484. }
  83485. }
  83486. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83487. // Listen for WebVR display changes
  83488. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83489. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83490. this._onVRRequestPresentStart = function () {
  83491. _this._webVRrequesting = true;
  83492. _this.updateButtonVisibility();
  83493. };
  83494. this._onVRRequestPresentComplete = function (success) {
  83495. _this._webVRrequesting = false;
  83496. _this.updateButtonVisibility();
  83497. };
  83498. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83499. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83500. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83501. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83502. scene.onDisposeObservable.add(function () {
  83503. _this.dispose();
  83504. });
  83505. // Gamepad connection events
  83506. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83507. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83508. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83509. this.updateButtonVisibility();
  83510. //create easing functions
  83511. this._circleEase = new BABYLON.CircleEase();
  83512. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83513. }
  83514. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83515. /** Return this.onEnteringVRObservable
  83516. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83517. */
  83518. get: function () {
  83519. return this.onEnteringVRObservable;
  83520. },
  83521. enumerable: true,
  83522. configurable: true
  83523. });
  83524. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83525. /** Return this.onExitingVRObservable
  83526. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83527. */
  83528. get: function () {
  83529. return this.onExitingVRObservable;
  83530. },
  83531. enumerable: true,
  83532. configurable: true
  83533. });
  83534. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83535. /** Return this.onControllerMeshLoadedObservable
  83536. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83537. */
  83538. get: function () {
  83539. return this.onControllerMeshLoadedObservable;
  83540. },
  83541. enumerable: true,
  83542. configurable: true
  83543. });
  83544. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83545. /**
  83546. * The mesh used to display where the user is going to teleport.
  83547. */
  83548. get: function () {
  83549. return this._teleportationTarget;
  83550. },
  83551. /**
  83552. * Sets the mesh to be used to display where the user is going to teleport.
  83553. */
  83554. set: function (value) {
  83555. if (value) {
  83556. value.name = "teleportationTarget";
  83557. this._isDefaultTeleportationTarget = false;
  83558. this._teleportationTarget = value;
  83559. }
  83560. },
  83561. enumerable: true,
  83562. configurable: true
  83563. });
  83564. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83565. /**
  83566. * The mesh used to display where the user is selecting,
  83567. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83568. * See http://doc.babylonjs.com/resources/baking_transformations
  83569. */
  83570. get: function () {
  83571. return this._cameraGazer._gazeTracker;
  83572. },
  83573. set: function (value) {
  83574. if (value) {
  83575. this._cameraGazer._gazeTracker = value;
  83576. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83577. this._cameraGazer._gazeTracker.isPickable = false;
  83578. this._cameraGazer._gazeTracker.isVisible = false;
  83579. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83580. if (this.leftController) {
  83581. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83582. }
  83583. if (this.rightController) {
  83584. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83585. }
  83586. }
  83587. },
  83588. enumerable: true,
  83589. configurable: true
  83590. });
  83591. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83592. /**
  83593. * If the ray of the gaze should be displayed.
  83594. */
  83595. get: function () {
  83596. return this._displayGaze;
  83597. },
  83598. /**
  83599. * Sets if the ray of the gaze should be displayed.
  83600. */
  83601. set: function (value) {
  83602. this._displayGaze = value;
  83603. if (!value) {
  83604. this._cameraGazer._gazeTracker.isVisible = false;
  83605. if (this.leftController) {
  83606. this.leftController._gazeTracker.isVisible = false;
  83607. }
  83608. if (this.rightController) {
  83609. this.rightController._gazeTracker.isVisible = false;
  83610. }
  83611. }
  83612. },
  83613. enumerable: true,
  83614. configurable: true
  83615. });
  83616. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83617. /**
  83618. * If the ray of the LaserPointer should be displayed.
  83619. */
  83620. get: function () {
  83621. return this._displayLaserPointer;
  83622. },
  83623. /**
  83624. * Sets if the ray of the LaserPointer should be displayed.
  83625. */
  83626. set: function (value) {
  83627. this._displayLaserPointer = value;
  83628. if (!value) {
  83629. if (this.rightController) {
  83630. this.rightController._deactivatePointer();
  83631. this.rightController._gazeTracker.isVisible = false;
  83632. }
  83633. if (this.leftController) {
  83634. this.leftController._deactivatePointer();
  83635. this.leftController._gazeTracker.isVisible = false;
  83636. }
  83637. }
  83638. else {
  83639. if (this.rightController) {
  83640. this.rightController._activatePointer();
  83641. }
  83642. else if (this.leftController) {
  83643. this.leftController._activatePointer();
  83644. }
  83645. }
  83646. },
  83647. enumerable: true,
  83648. configurable: true
  83649. });
  83650. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83651. /**
  83652. * The deviceOrientationCamera used as the camera when not in VR.
  83653. */
  83654. get: function () {
  83655. return this._deviceOrientationCamera;
  83656. },
  83657. enumerable: true,
  83658. configurable: true
  83659. });
  83660. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83661. /**
  83662. * Based on the current WebVR support, returns the current VR camera used.
  83663. */
  83664. get: function () {
  83665. if (this._webVRready) {
  83666. return this._webVRCamera;
  83667. }
  83668. else {
  83669. return this._scene.activeCamera;
  83670. }
  83671. },
  83672. enumerable: true,
  83673. configurable: true
  83674. });
  83675. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83676. /**
  83677. * The webVRCamera which is used when in VR.
  83678. */
  83679. get: function () {
  83680. return this._webVRCamera;
  83681. },
  83682. enumerable: true,
  83683. configurable: true
  83684. });
  83685. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83686. /**
  83687. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83688. */
  83689. get: function () {
  83690. return this._vrDeviceOrientationCamera;
  83691. },
  83692. enumerable: true,
  83693. configurable: true
  83694. });
  83695. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83696. get: function () {
  83697. var result = this._cameraGazer._teleportationRequestInitiated
  83698. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83699. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83700. return result;
  83701. },
  83702. enumerable: true,
  83703. configurable: true
  83704. });
  83705. // Raised when one of the controller has loaded successfully its associated default mesh
  83706. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83707. if (this.leftController && this.leftController.webVRController == webVRController) {
  83708. if (webVRController.mesh) {
  83709. this.leftController._setLaserPointerParent(webVRController.mesh);
  83710. }
  83711. }
  83712. if (this.rightController && this.rightController.webVRController == webVRController) {
  83713. if (webVRController.mesh) {
  83714. this.rightController._setLaserPointerParent(webVRController.mesh);
  83715. }
  83716. }
  83717. try {
  83718. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83719. }
  83720. catch (err) {
  83721. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83722. }
  83723. };
  83724. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83725. /**
  83726. * Gets a value indicating if we are currently in VR mode.
  83727. */
  83728. get: function () {
  83729. return this._webVRpresenting || this._fullscreenVRpresenting;
  83730. },
  83731. enumerable: true,
  83732. configurable: true
  83733. });
  83734. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83735. var vrDisplay = this._scene.getEngine().getVRDevice();
  83736. if (vrDisplay) {
  83737. var wasPresenting = this._webVRpresenting;
  83738. // A VR display is connected
  83739. this._webVRpresenting = vrDisplay.isPresenting;
  83740. if (wasPresenting && !this._webVRpresenting)
  83741. this.exitVR();
  83742. }
  83743. else {
  83744. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83745. }
  83746. this.updateButtonVisibility();
  83747. };
  83748. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83749. this._webVRsupported = eventArgs.vrSupported;
  83750. this._webVRready = !!eventArgs.vrDisplay;
  83751. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83752. this.updateButtonVisibility();
  83753. };
  83754. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83755. if (this._canvas && !this._useCustomVRButton) {
  83756. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83757. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83758. }
  83759. };
  83760. VRExperienceHelper.prototype.displayVRButton = function () {
  83761. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83762. document.body.appendChild(this._btnVR);
  83763. this._btnVRDisplayed = true;
  83764. }
  83765. };
  83766. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83767. if (!this._btnVR || this._useCustomVRButton) {
  83768. return;
  83769. }
  83770. this._btnVR.className = "babylonVRicon";
  83771. if (this.isInVRMode) {
  83772. this._btnVR.className += " vrdisplaypresenting";
  83773. }
  83774. else {
  83775. if (this._webVRready)
  83776. this._btnVR.className += " vrdisplayready";
  83777. if (this._webVRsupported)
  83778. this._btnVR.className += " vrdisplaysupported";
  83779. if (this._webVRrequesting)
  83780. this._btnVR.className += " vrdisplayrequesting";
  83781. }
  83782. };
  83783. /**
  83784. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83785. * Otherwise, will use the fullscreen API.
  83786. */
  83787. VRExperienceHelper.prototype.enterVR = function () {
  83788. if (this.onEnteringVRObservable) {
  83789. try {
  83790. this.onEnteringVRObservable.notifyObservers(this);
  83791. }
  83792. catch (err) {
  83793. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83794. }
  83795. }
  83796. if (this._scene.activeCamera) {
  83797. this._position = this._scene.activeCamera.position.clone();
  83798. // make sure that we return to the last active camera
  83799. this._existingCamera = this._scene.activeCamera;
  83800. }
  83801. if (this._webVRrequesting)
  83802. return;
  83803. // If WebVR is supported and a headset is connected
  83804. if (this._webVRready) {
  83805. if (!this._webVRpresenting) {
  83806. this._webVRCamera.position = this._position;
  83807. this._scene.activeCamera = this._webVRCamera;
  83808. }
  83809. }
  83810. else if (this._vrDeviceOrientationCamera) {
  83811. this._vrDeviceOrientationCamera.position = this._position;
  83812. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83813. this._scene.getEngine().switchFullscreen(true);
  83814. this.updateButtonVisibility();
  83815. }
  83816. if (this._scene.activeCamera && this._canvas) {
  83817. this._scene.activeCamera.attachControl(this._canvas);
  83818. }
  83819. if (this._interactionsEnabled) {
  83820. this._scene.registerBeforeRender(this.beforeRender);
  83821. }
  83822. };
  83823. /**
  83824. * Attempt to exit VR, or fullscreen.
  83825. */
  83826. VRExperienceHelper.prototype.exitVR = function () {
  83827. if (this.onExitingVRObservable) {
  83828. try {
  83829. this.onExitingVRObservable.notifyObservers(this);
  83830. }
  83831. catch (err) {
  83832. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83833. }
  83834. }
  83835. if (this._webVRpresenting) {
  83836. this._scene.getEngine().disableVR();
  83837. }
  83838. if (this._scene.activeCamera) {
  83839. this._position = this._scene.activeCamera.position.clone();
  83840. }
  83841. if (this._deviceOrientationCamera) {
  83842. this._deviceOrientationCamera.position = this._position;
  83843. this._scene.activeCamera = this._deviceOrientationCamera;
  83844. if (this._canvas) {
  83845. this._scene.activeCamera.attachControl(this._canvas);
  83846. }
  83847. }
  83848. else if (this._existingCamera) {
  83849. this._existingCamera.position = this._position;
  83850. this._scene.activeCamera = this._existingCamera;
  83851. }
  83852. this.updateButtonVisibility();
  83853. if (this._interactionsEnabled) {
  83854. this._scene.unregisterBeforeRender(this.beforeRender);
  83855. }
  83856. };
  83857. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83858. /**
  83859. * The position of the vr experience helper.
  83860. */
  83861. get: function () {
  83862. return this._position;
  83863. },
  83864. /**
  83865. * Sets the position of the vr experience helper.
  83866. */
  83867. set: function (value) {
  83868. this._position = value;
  83869. if (this._scene.activeCamera) {
  83870. this._scene.activeCamera.position = value;
  83871. }
  83872. },
  83873. enumerable: true,
  83874. configurable: true
  83875. });
  83876. /**
  83877. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83878. */
  83879. VRExperienceHelper.prototype.enableInteractions = function () {
  83880. var _this = this;
  83881. if (!this._interactionsEnabled) {
  83882. this._interactionsRequested = true;
  83883. if (this.leftController) {
  83884. this._enableInteractionOnController(this.leftController);
  83885. }
  83886. if (this.rightController) {
  83887. this._enableInteractionOnController(this.rightController);
  83888. }
  83889. this.raySelectionPredicate = function (mesh) {
  83890. return mesh.isVisible;
  83891. };
  83892. this.meshSelectionPredicate = function (mesh) {
  83893. return true;
  83894. };
  83895. this._raySelectionPredicate = function (mesh) {
  83896. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83897. && mesh.name.indexOf("teleportationTarget") === -1
  83898. && mesh.name.indexOf("torusTeleportation") === -1
  83899. && mesh.name.indexOf("laserPointer") === -1)) {
  83900. return _this.raySelectionPredicate(mesh);
  83901. }
  83902. return false;
  83903. };
  83904. this._interactionsEnabled = true;
  83905. }
  83906. };
  83907. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83908. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83909. if (this._floorMeshesCollection[i].id === mesh.id) {
  83910. return true;
  83911. }
  83912. }
  83913. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83914. return true;
  83915. }
  83916. return false;
  83917. };
  83918. /**
  83919. * Adds a floor mesh to be used for teleportation.
  83920. * @param floorMesh the mesh to be used for teleportation.
  83921. */
  83922. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83923. if (!this._floorMeshesCollection) {
  83924. return;
  83925. }
  83926. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83927. return;
  83928. }
  83929. this._floorMeshesCollection.push(floorMesh);
  83930. };
  83931. /**
  83932. * Removes a floor mesh from being used for teleportation.
  83933. * @param floorMesh the mesh to be removed.
  83934. */
  83935. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83936. if (!this._floorMeshesCollection) {
  83937. return;
  83938. }
  83939. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83940. if (meshIndex !== -1) {
  83941. this._floorMeshesCollection.splice(meshIndex, 1);
  83942. }
  83943. };
  83944. /**
  83945. * Enables interactions and teleportation using the VR controllers and gaze.
  83946. * @param vrTeleportationOptions options to modify teleportation behavior.
  83947. */
  83948. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83949. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83950. if (!this._teleportationInitialized) {
  83951. this._teleportationRequested = true;
  83952. this.enableInteractions();
  83953. if (vrTeleportationOptions.floorMeshName) {
  83954. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83955. }
  83956. if (vrTeleportationOptions.floorMeshes) {
  83957. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83958. }
  83959. if (this.leftController != null) {
  83960. this._enableTeleportationOnController(this.leftController);
  83961. }
  83962. if (this.rightController != null) {
  83963. this._enableTeleportationOnController(this.rightController);
  83964. }
  83965. // Creates an image processing post process for the vignette not relying
  83966. // on the main scene configuration for image processing to reduce setup and spaces
  83967. // (gamma/linear) conflicts.
  83968. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83969. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83970. imageProcessingConfiguration.vignetteEnabled = true;
  83971. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83972. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83973. this._teleportationInitialized = true;
  83974. if (this._isDefaultTeleportationTarget) {
  83975. this._createTeleportationCircles();
  83976. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83977. }
  83978. }
  83979. };
  83980. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83981. var _this = this;
  83982. var controllerMesh = controller.webVRController.mesh;
  83983. if (controllerMesh) {
  83984. controller._interactionsEnabled = true;
  83985. controller._activatePointer();
  83986. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83987. // Enabling / disabling laserPointer
  83988. if (_this._displayLaserPointer && stateObject.value === 1) {
  83989. if (controller._activePointer) {
  83990. controller._deactivatePointer();
  83991. }
  83992. else {
  83993. controller._activatePointer();
  83994. }
  83995. if (_this.displayGaze) {
  83996. controller._gazeTracker.isVisible = controller._activePointer;
  83997. }
  83998. }
  83999. });
  84000. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  84001. if (!controller._pointerDownOnMeshAsked) {
  84002. if (stateObject.value > _this._padSensibilityUp) {
  84003. controller._selectionPointerDown();
  84004. }
  84005. }
  84006. else if (stateObject.value < _this._padSensibilityDown) {
  84007. controller._selectionPointerUp();
  84008. }
  84009. });
  84010. }
  84011. };
  84012. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  84013. // Dont teleport if another gaze already requested teleportation
  84014. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  84015. return;
  84016. }
  84017. if (!gazer._teleportationRequestInitiated) {
  84018. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  84019. gazer._activatePointer();
  84020. gazer._teleportationRequestInitiated = true;
  84021. }
  84022. }
  84023. else {
  84024. // Listening to the proper controller values changes to confirm teleportation
  84025. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  84026. if (this._teleportActive) {
  84027. this._teleportCamera(this._haloCenter);
  84028. }
  84029. gazer._teleportationRequestInitiated = false;
  84030. }
  84031. }
  84032. };
  84033. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  84034. // Only rotate when user is not currently selecting a teleportation location
  84035. if (gazer._teleportationRequestInitiated) {
  84036. return;
  84037. }
  84038. if (!this._rotationLeftAsked) {
  84039. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  84040. this._rotationLeftAsked = true;
  84041. if (this._rotationAllowed) {
  84042. this._rotateCamera(false);
  84043. }
  84044. }
  84045. }
  84046. else {
  84047. if (stateObject.x > -this._padSensibilityDown) {
  84048. this._rotationLeftAsked = false;
  84049. }
  84050. }
  84051. if (!this._rotationRightAsked) {
  84052. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  84053. this._rotationRightAsked = true;
  84054. if (this._rotationAllowed) {
  84055. this._rotateCamera(true);
  84056. }
  84057. }
  84058. }
  84059. else {
  84060. if (stateObject.x < this._padSensibilityDown) {
  84061. this._rotationRightAsked = false;
  84062. }
  84063. }
  84064. };
  84065. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  84066. // Only teleport backwards when user is not currently selecting a teleportation location
  84067. if (gazer._teleportationRequestInitiated) {
  84068. return;
  84069. }
  84070. // Teleport backwards
  84071. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  84072. if (!gazer._teleportationBackRequestInitiated) {
  84073. if (!this.currentVRCamera) {
  84074. return;
  84075. }
  84076. // Get rotation and position of the current camera
  84077. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  84078. var position = this.currentVRCamera.position;
  84079. // If the camera has device position, use that instead
  84080. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  84081. rotation = this.currentVRCamera.deviceRotationQuaternion;
  84082. position = this.currentVRCamera.devicePosition;
  84083. }
  84084. // Get matrix with only the y rotation of the device rotation
  84085. rotation.toEulerAnglesToRef(this._workingVector);
  84086. this._workingVector.z = 0;
  84087. this._workingVector.x = 0;
  84088. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  84089. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  84090. // Rotate backwards ray by device rotation to cast at the ground behind the user
  84091. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  84092. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  84093. var ray = new BABYLON.Ray(position, this._workingVector);
  84094. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  84095. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  84096. this._teleportCamera(hit.pickedPoint);
  84097. }
  84098. gazer._teleportationBackRequestInitiated = true;
  84099. }
  84100. }
  84101. else {
  84102. gazer._teleportationBackRequestInitiated = false;
  84103. }
  84104. };
  84105. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  84106. var _this = this;
  84107. var controllerMesh = controller.webVRController.mesh;
  84108. if (controllerMesh) {
  84109. if (!controller._interactionsEnabled) {
  84110. this._enableInteractionOnController(controller);
  84111. }
  84112. controller._interactionsEnabled = true;
  84113. controller._teleportationEnabled = true;
  84114. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  84115. controller._dpadPressed = false;
  84116. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  84117. controller._dpadPressed = stateObject.pressed;
  84118. if (!controller._dpadPressed) {
  84119. _this._rotationLeftAsked = false;
  84120. _this._rotationRightAsked = false;
  84121. controller._teleportationBackRequestInitiated = false;
  84122. }
  84123. });
  84124. }
  84125. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  84126. if (_this.teleportationEnabled) {
  84127. _this._checkTeleportBackwards(stateObject, controller);
  84128. _this._checkTeleportWithRay(stateObject, controller);
  84129. }
  84130. _this._checkRotate(stateObject, controller);
  84131. });
  84132. }
  84133. };
  84134. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  84135. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  84136. this._teleportationTarget.isPickable = false;
  84137. var length = 512;
  84138. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  84139. dynamicTexture.hasAlpha = true;
  84140. var context = dynamicTexture.getContext();
  84141. var centerX = length / 2;
  84142. var centerY = length / 2;
  84143. var radius = 200;
  84144. context.beginPath();
  84145. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  84146. context.fillStyle = this._teleportationFillColor;
  84147. context.fill();
  84148. context.lineWidth = 10;
  84149. context.strokeStyle = this._teleportationBorderColor;
  84150. context.stroke();
  84151. context.closePath();
  84152. dynamicTexture.update();
  84153. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  84154. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  84155. this._teleportationTarget.material = teleportationCircleMaterial;
  84156. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  84157. torus.isPickable = false;
  84158. torus.parent = this._teleportationTarget;
  84159. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  84160. var keys = [];
  84161. keys.push({
  84162. frame: 0,
  84163. value: 0
  84164. });
  84165. keys.push({
  84166. frame: 30,
  84167. value: 0.4
  84168. });
  84169. keys.push({
  84170. frame: 60,
  84171. value: 0
  84172. });
  84173. animationInnerCircle.setKeys(keys);
  84174. var easingFunction = new BABYLON.SineEase();
  84175. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  84176. animationInnerCircle.setEasingFunction(easingFunction);
  84177. torus.animations = [];
  84178. torus.animations.push(animationInnerCircle);
  84179. this._scene.beginAnimation(torus, 0, 60, true);
  84180. this._hideTeleportationTarget();
  84181. };
  84182. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  84183. this._teleportActive = true;
  84184. if (this._teleportationInitialized) {
  84185. this._teleportationTarget.isVisible = true;
  84186. if (this._isDefaultTeleportationTarget) {
  84187. this._teleportationTarget.getChildren()[0].isVisible = true;
  84188. }
  84189. }
  84190. };
  84191. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  84192. this._teleportActive = false;
  84193. if (this._teleportationInitialized) {
  84194. this._teleportationTarget.isVisible = false;
  84195. if (this._isDefaultTeleportationTarget) {
  84196. this._teleportationTarget.getChildren()[0].isVisible = false;
  84197. }
  84198. }
  84199. };
  84200. VRExperienceHelper.prototype._rotateCamera = function (right) {
  84201. var _this = this;
  84202. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84203. return;
  84204. }
  84205. if (right) {
  84206. this._rotationAngle++;
  84207. }
  84208. else {
  84209. this._rotationAngle--;
  84210. }
  84211. this.currentVRCamera.animations = [];
  84212. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  84213. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84214. var animationRotationKeys = [];
  84215. animationRotationKeys.push({
  84216. frame: 0,
  84217. value: this.currentVRCamera.rotationQuaternion
  84218. });
  84219. animationRotationKeys.push({
  84220. frame: 6,
  84221. value: target
  84222. });
  84223. animationRotation.setKeys(animationRotationKeys);
  84224. animationRotation.setEasingFunction(this._circleEase);
  84225. this.currentVRCamera.animations.push(animationRotation);
  84226. this._postProcessMove.animations = [];
  84227. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84228. var vignetteWeightKeys = [];
  84229. vignetteWeightKeys.push({
  84230. frame: 0,
  84231. value: 0
  84232. });
  84233. vignetteWeightKeys.push({
  84234. frame: 3,
  84235. value: 4
  84236. });
  84237. vignetteWeightKeys.push({
  84238. frame: 6,
  84239. value: 0
  84240. });
  84241. animationPP.setKeys(vignetteWeightKeys);
  84242. animationPP.setEasingFunction(this._circleEase);
  84243. this._postProcessMove.animations.push(animationPP);
  84244. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84245. var vignetteStretchKeys = [];
  84246. vignetteStretchKeys.push({
  84247. frame: 0,
  84248. value: 0
  84249. });
  84250. vignetteStretchKeys.push({
  84251. frame: 3,
  84252. value: 10
  84253. });
  84254. vignetteStretchKeys.push({
  84255. frame: 6,
  84256. value: 0
  84257. });
  84258. animationPP2.setKeys(vignetteStretchKeys);
  84259. animationPP2.setEasingFunction(this._circleEase);
  84260. this._postProcessMove.animations.push(animationPP2);
  84261. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84262. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84263. this._postProcessMove.samples = 4;
  84264. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84265. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  84266. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84267. });
  84268. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  84269. };
  84270. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  84271. if (hit.pickedPoint) {
  84272. if (gazer._teleportationRequestInitiated) {
  84273. this._displayTeleportationTarget();
  84274. this._haloCenter.copyFrom(hit.pickedPoint);
  84275. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  84276. }
  84277. var pickNormal = hit.getNormal(true, false);
  84278. if (pickNormal) {
  84279. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84280. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84281. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  84282. }
  84283. this._teleportationTarget.position.y += 0.1;
  84284. }
  84285. };
  84286. VRExperienceHelper.prototype._teleportCamera = function (location) {
  84287. var _this = this;
  84288. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84289. return;
  84290. }
  84291. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  84292. // offset of the headset from the anchor.
  84293. if (this.webVRCamera.leftCamera) {
  84294. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  84295. this._workingVector.subtractInPlace(this.webVRCamera.position);
  84296. location.subtractToRef(this._workingVector, this._workingVector);
  84297. }
  84298. else {
  84299. this._workingVector.copyFrom(location);
  84300. }
  84301. // Add height to account for user's height offset
  84302. if (this.isInVRMode) {
  84303. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  84304. }
  84305. else {
  84306. this._workingVector.y += this._defaultHeight;
  84307. }
  84308. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  84309. // Create animation from the camera's position to the new location
  84310. this.currentVRCamera.animations = [];
  84311. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84312. var animationCameraTeleportationKeys = [{
  84313. frame: 0,
  84314. value: this.currentVRCamera.position
  84315. },
  84316. {
  84317. frame: 11,
  84318. value: this._workingVector
  84319. }
  84320. ];
  84321. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  84322. animationCameraTeleportation.setEasingFunction(this._circleEase);
  84323. this.currentVRCamera.animations.push(animationCameraTeleportation);
  84324. this._postProcessMove.animations = [];
  84325. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84326. var vignetteWeightKeys = [];
  84327. vignetteWeightKeys.push({
  84328. frame: 0,
  84329. value: 0
  84330. });
  84331. vignetteWeightKeys.push({
  84332. frame: 5,
  84333. value: 8
  84334. });
  84335. vignetteWeightKeys.push({
  84336. frame: 11,
  84337. value: 0
  84338. });
  84339. animationPP.setKeys(vignetteWeightKeys);
  84340. this._postProcessMove.animations.push(animationPP);
  84341. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84342. var vignetteStretchKeys = [];
  84343. vignetteStretchKeys.push({
  84344. frame: 0,
  84345. value: 0
  84346. });
  84347. vignetteStretchKeys.push({
  84348. frame: 5,
  84349. value: 10
  84350. });
  84351. vignetteStretchKeys.push({
  84352. frame: 11,
  84353. value: 0
  84354. });
  84355. animationPP2.setKeys(vignetteStretchKeys);
  84356. this._postProcessMove.animations.push(animationPP2);
  84357. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84358. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84359. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84360. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84361. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84362. });
  84363. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84364. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84365. });
  84366. this._hideTeleportationTarget();
  84367. };
  84368. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84369. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84370. return;
  84371. }
  84372. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84373. // Moving the gazeTracker on the mesh face targetted
  84374. if (hit && hit.pickedPoint) {
  84375. if (this._displayGaze) {
  84376. var multiplier = 1;
  84377. gazer._gazeTracker.isVisible = true;
  84378. if (gazer._isActionableMesh) {
  84379. multiplier = 3;
  84380. }
  84381. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84382. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84383. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84384. var pickNormal = hit.getNormal();
  84385. // To avoid z-fighting
  84386. var deltaFighting = 0.002;
  84387. if (pickNormal) {
  84388. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84389. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84390. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84391. }
  84392. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84393. if (gazer._gazeTracker.position.x < 0) {
  84394. gazer._gazeTracker.position.x += deltaFighting;
  84395. }
  84396. else {
  84397. gazer._gazeTracker.position.x -= deltaFighting;
  84398. }
  84399. if (gazer._gazeTracker.position.y < 0) {
  84400. gazer._gazeTracker.position.y += deltaFighting;
  84401. }
  84402. else {
  84403. gazer._gazeTracker.position.y -= deltaFighting;
  84404. }
  84405. if (gazer._gazeTracker.position.z < 0) {
  84406. gazer._gazeTracker.position.z += deltaFighting;
  84407. }
  84408. else {
  84409. gazer._gazeTracker.position.z -= deltaFighting;
  84410. }
  84411. }
  84412. // Changing the size of the laser pointer based on the distance from the targetted point
  84413. gazer._updatePointerDistance(hit.distance);
  84414. }
  84415. else {
  84416. gazer._gazeTracker.isVisible = false;
  84417. }
  84418. if (hit && hit.pickedMesh) {
  84419. gazer._currentHit = hit;
  84420. if (gazer._pointerDownOnMeshAsked) {
  84421. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84422. }
  84423. // The object selected is the floor, we're in a teleportation scenario
  84424. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84425. // Moving the teleportation area to this targetted point
  84426. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84427. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84428. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84429. }
  84430. gazer._currentMeshSelected = null;
  84431. if (gazer._teleportationRequestInitiated) {
  84432. this._moveTeleportationSelectorTo(hit, gazer);
  84433. }
  84434. return;
  84435. }
  84436. // If not, we're in a selection scenario
  84437. //this._teleportationAllowed = false;
  84438. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84439. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84440. this.onNewMeshPicked.notifyObservers(hit);
  84441. gazer._currentMeshSelected = hit.pickedMesh;
  84442. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84443. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84444. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84445. gazer._isActionableMesh = true;
  84446. }
  84447. else {
  84448. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84449. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84450. gazer._isActionableMesh = false;
  84451. }
  84452. try {
  84453. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84454. }
  84455. catch (err) {
  84456. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84457. }
  84458. }
  84459. else {
  84460. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84461. gazer._currentMeshSelected = null;
  84462. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84463. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84464. }
  84465. }
  84466. }
  84467. else {
  84468. gazer._currentHit = null;
  84469. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84470. gazer._currentMeshSelected = null;
  84471. //this._teleportationAllowed = false;
  84472. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84473. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84474. }
  84475. };
  84476. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84477. if (mesh) {
  84478. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84479. }
  84480. };
  84481. /**
  84482. * Sets the color of the laser ray from the vr controllers.
  84483. * @param color new color for the ray.
  84484. */
  84485. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84486. if (this.leftController) {
  84487. this.leftController._setLaserPointerColor(color);
  84488. }
  84489. if (this.rightController) {
  84490. this.rightController._setLaserPointerColor(color);
  84491. }
  84492. };
  84493. /**
  84494. * Sets the color of the ray from the vr headsets gaze.
  84495. * @param color new color for the ray.
  84496. */
  84497. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84498. if (!this._cameraGazer._gazeTracker.material) {
  84499. return;
  84500. }
  84501. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84502. if (this.leftController) {
  84503. this.leftController._gazeTracker.material.emissiveColor = color;
  84504. }
  84505. if (this.rightController) {
  84506. this.rightController._gazeTracker.material.emissiveColor = color;
  84507. }
  84508. };
  84509. /**
  84510. * Exits VR and disposes of the vr experience helper
  84511. */
  84512. VRExperienceHelper.prototype.dispose = function () {
  84513. if (this.isInVRMode) {
  84514. this.exitVR();
  84515. }
  84516. if (this._postProcessMove) {
  84517. this._postProcessMove.dispose();
  84518. }
  84519. if (this._webVRCamera) {
  84520. this._webVRCamera.dispose();
  84521. }
  84522. if (this._vrDeviceOrientationCamera) {
  84523. this._vrDeviceOrientationCamera.dispose();
  84524. }
  84525. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84526. document.body.removeChild(this._btnVR);
  84527. }
  84528. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84529. this._deviceOrientationCamera.dispose();
  84530. }
  84531. if (this._cameraGazer) {
  84532. this._cameraGazer.dispose();
  84533. }
  84534. if (this.leftController) {
  84535. this.leftController.dispose();
  84536. }
  84537. if (this.rightController) {
  84538. this.rightController.dispose();
  84539. }
  84540. if (this._teleportationTarget) {
  84541. this._teleportationTarget.dispose();
  84542. }
  84543. this._floorMeshesCollection = [];
  84544. document.removeEventListener("keydown", this._onKeyDown);
  84545. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84546. window.removeEventListener("resize", this._onResize);
  84547. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84548. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84549. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84550. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84551. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84552. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84553. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84554. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84555. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84556. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84557. this._scene.unregisterBeforeRender(this.beforeRender);
  84558. };
  84559. /**
  84560. * Gets the name of the VRExperienceHelper class
  84561. * @returns "VRExperienceHelper"
  84562. */
  84563. VRExperienceHelper.prototype.getClassName = function () {
  84564. return "VRExperienceHelper";
  84565. };
  84566. return VRExperienceHelper;
  84567. }());
  84568. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84569. })(BABYLON || (BABYLON = {}));
  84570. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84571. "use strict";
  84572. // Mainly based on these 2 articles :
  84573. // 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
  84574. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84575. var BABYLON;
  84576. (function (BABYLON) {
  84577. var JoystickAxis;
  84578. (function (JoystickAxis) {
  84579. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84580. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84581. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84582. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84583. var VirtualJoystick = /** @class */ (function () {
  84584. function VirtualJoystick(leftJoystick) {
  84585. var _this = this;
  84586. if (leftJoystick) {
  84587. this._leftJoystick = true;
  84588. }
  84589. else {
  84590. this._leftJoystick = false;
  84591. }
  84592. VirtualJoystick._globalJoystickIndex++;
  84593. // By default left & right arrow keys are moving the X
  84594. // and up & down keys are moving the Y
  84595. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84596. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84597. this.reverseLeftRight = false;
  84598. this.reverseUpDown = false;
  84599. // collections of pointers
  84600. this._touches = new BABYLON.StringDictionary();
  84601. this.deltaPosition = BABYLON.Vector3.Zero();
  84602. this._joystickSensibility = 25;
  84603. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84604. this._onResize = function (evt) {
  84605. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84606. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84607. if (VirtualJoystick.vjCanvas) {
  84608. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84609. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84610. }
  84611. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84612. };
  84613. // injecting a canvas element on top of the canvas 3D game
  84614. if (!VirtualJoystick.vjCanvas) {
  84615. window.addEventListener("resize", this._onResize, false);
  84616. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84617. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84618. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84619. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84620. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84621. VirtualJoystick.vjCanvas.style.width = "100%";
  84622. VirtualJoystick.vjCanvas.style.height = "100%";
  84623. VirtualJoystick.vjCanvas.style.position = "absolute";
  84624. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84625. VirtualJoystick.vjCanvas.style.top = "0px";
  84626. VirtualJoystick.vjCanvas.style.left = "0px";
  84627. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84628. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84629. // Support for jQuery PEP polyfill
  84630. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84631. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84632. if (!context) {
  84633. throw new Error("Unable to create canvas for virtual joystick");
  84634. }
  84635. VirtualJoystick.vjCanvasContext = context;
  84636. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84637. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84638. document.body.appendChild(VirtualJoystick.vjCanvas);
  84639. }
  84640. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84641. this.pressed = false;
  84642. // default joystick color
  84643. this._joystickColor = "cyan";
  84644. this._joystickPointerID = -1;
  84645. // current joystick position
  84646. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84647. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84648. // origin joystick position
  84649. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84650. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84651. this._onPointerDownHandlerRef = function (evt) {
  84652. _this._onPointerDown(evt);
  84653. };
  84654. this._onPointerMoveHandlerRef = function (evt) {
  84655. _this._onPointerMove(evt);
  84656. };
  84657. this._onPointerUpHandlerRef = function (evt) {
  84658. _this._onPointerUp(evt);
  84659. };
  84660. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84661. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84662. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84663. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84664. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84665. evt.preventDefault(); // Disables system menu
  84666. }, false);
  84667. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84668. }
  84669. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84670. this._joystickSensibility = newJoystickSensibility;
  84671. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84672. };
  84673. VirtualJoystick.prototype._onPointerDown = function (e) {
  84674. var positionOnScreenCondition;
  84675. e.preventDefault();
  84676. if (this._leftJoystick === true) {
  84677. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84678. }
  84679. else {
  84680. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84681. }
  84682. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84683. // First contact will be dedicated to the virtual joystick
  84684. this._joystickPointerID = e.pointerId;
  84685. this._joystickPointerStartPos.x = e.clientX;
  84686. this._joystickPointerStartPos.y = e.clientY;
  84687. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84688. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84689. this._deltaJoystickVector.x = 0;
  84690. this._deltaJoystickVector.y = 0;
  84691. this.pressed = true;
  84692. this._touches.add(e.pointerId.toString(), e);
  84693. }
  84694. else {
  84695. // You can only trigger the action buttons with a joystick declared
  84696. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84697. this._action();
  84698. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84699. }
  84700. }
  84701. };
  84702. VirtualJoystick.prototype._onPointerMove = function (e) {
  84703. // If the current pointer is the one associated to the joystick (first touch contact)
  84704. if (this._joystickPointerID == e.pointerId) {
  84705. this._joystickPointerPos.x = e.clientX;
  84706. this._joystickPointerPos.y = e.clientY;
  84707. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84708. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84709. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84710. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84711. switch (this._axisTargetedByLeftAndRight) {
  84712. case JoystickAxis.X:
  84713. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84714. break;
  84715. case JoystickAxis.Y:
  84716. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84717. break;
  84718. case JoystickAxis.Z:
  84719. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84720. break;
  84721. }
  84722. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84723. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84724. switch (this._axisTargetedByUpAndDown) {
  84725. case JoystickAxis.X:
  84726. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84727. break;
  84728. case JoystickAxis.Y:
  84729. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84730. break;
  84731. case JoystickAxis.Z:
  84732. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84733. break;
  84734. }
  84735. }
  84736. else {
  84737. var data = this._touches.get(e.pointerId.toString());
  84738. if (data) {
  84739. data.x = e.clientX;
  84740. data.y = e.clientY;
  84741. }
  84742. }
  84743. };
  84744. VirtualJoystick.prototype._onPointerUp = function (e) {
  84745. if (this._joystickPointerID == e.pointerId) {
  84746. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84747. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84748. this._joystickPointerID = -1;
  84749. this.pressed = false;
  84750. }
  84751. else {
  84752. var touch = this._touches.get(e.pointerId.toString());
  84753. if (touch) {
  84754. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84755. }
  84756. }
  84757. this._deltaJoystickVector.x = 0;
  84758. this._deltaJoystickVector.y = 0;
  84759. this._touches.remove(e.pointerId.toString());
  84760. };
  84761. /**
  84762. * Change the color of the virtual joystick
  84763. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84764. */
  84765. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84766. this._joystickColor = newColor;
  84767. };
  84768. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84769. this._action = action;
  84770. };
  84771. // Define which axis you'd like to control for left & right
  84772. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84773. switch (axis) {
  84774. case JoystickAxis.X:
  84775. case JoystickAxis.Y:
  84776. case JoystickAxis.Z:
  84777. this._axisTargetedByLeftAndRight = axis;
  84778. break;
  84779. default:
  84780. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84781. break;
  84782. }
  84783. };
  84784. // Define which axis you'd like to control for up & down
  84785. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84786. switch (axis) {
  84787. case JoystickAxis.X:
  84788. case JoystickAxis.Y:
  84789. case JoystickAxis.Z:
  84790. this._axisTargetedByUpAndDown = axis;
  84791. break;
  84792. default:
  84793. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84794. break;
  84795. }
  84796. };
  84797. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84798. var _this = this;
  84799. if (this.pressed) {
  84800. this._touches.forEach(function (key, touch) {
  84801. if (touch.pointerId === _this._joystickPointerID) {
  84802. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84803. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84804. VirtualJoystick.vjCanvasContext.beginPath();
  84805. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84806. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84807. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84808. VirtualJoystick.vjCanvasContext.stroke();
  84809. VirtualJoystick.vjCanvasContext.closePath();
  84810. VirtualJoystick.vjCanvasContext.beginPath();
  84811. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84812. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84813. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84814. VirtualJoystick.vjCanvasContext.stroke();
  84815. VirtualJoystick.vjCanvasContext.closePath();
  84816. VirtualJoystick.vjCanvasContext.beginPath();
  84817. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84818. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84819. VirtualJoystick.vjCanvasContext.stroke();
  84820. VirtualJoystick.vjCanvasContext.closePath();
  84821. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84822. }
  84823. else {
  84824. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84825. VirtualJoystick.vjCanvasContext.beginPath();
  84826. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84827. VirtualJoystick.vjCanvasContext.beginPath();
  84828. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84829. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84830. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84831. VirtualJoystick.vjCanvasContext.stroke();
  84832. VirtualJoystick.vjCanvasContext.closePath();
  84833. touch.prevX = touch.x;
  84834. touch.prevY = touch.y;
  84835. }
  84836. ;
  84837. });
  84838. }
  84839. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84840. };
  84841. VirtualJoystick.prototype.releaseCanvas = function () {
  84842. if (VirtualJoystick.vjCanvas) {
  84843. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84844. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84845. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84846. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84847. window.removeEventListener("resize", this._onResize);
  84848. document.body.removeChild(VirtualJoystick.vjCanvas);
  84849. VirtualJoystick.vjCanvas = null;
  84850. }
  84851. };
  84852. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84853. VirtualJoystick._globalJoystickIndex = 0;
  84854. return VirtualJoystick;
  84855. }());
  84856. BABYLON.VirtualJoystick = VirtualJoystick;
  84857. })(BABYLON || (BABYLON = {}));
  84858. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84859. "use strict";
  84860. var BABYLON;
  84861. (function (BABYLON) {
  84862. // We're mainly based on the logic defined into the FreeCamera code
  84863. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84864. __extends(VirtualJoysticksCamera, _super);
  84865. function VirtualJoysticksCamera(name, position, scene) {
  84866. var _this = _super.call(this, name, position, scene) || this;
  84867. _this.inputs.addVirtualJoystick();
  84868. return _this;
  84869. }
  84870. VirtualJoysticksCamera.prototype.getClassName = function () {
  84871. return "VirtualJoysticksCamera";
  84872. };
  84873. return VirtualJoysticksCamera;
  84874. }(BABYLON.FreeCamera));
  84875. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84876. })(BABYLON || (BABYLON = {}));
  84877. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84878. "use strict";
  84879. var BABYLON;
  84880. (function (BABYLON) {
  84881. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84882. function FreeCameraVirtualJoystickInput() {
  84883. }
  84884. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84885. return this._leftjoystick;
  84886. };
  84887. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84888. return this._rightjoystick;
  84889. };
  84890. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84891. if (this._leftjoystick) {
  84892. var camera = this.camera;
  84893. var speed = camera._computeLocalCameraSpeed() * 50;
  84894. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84895. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84896. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84897. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84898. if (!this._leftjoystick.pressed) {
  84899. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84900. }
  84901. if (!this._rightjoystick.pressed) {
  84902. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84903. }
  84904. }
  84905. };
  84906. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84907. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84908. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84909. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84910. this._leftjoystick.setJoystickSensibility(0.15);
  84911. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84912. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84913. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84914. this._rightjoystick.reverseUpDown = true;
  84915. this._rightjoystick.setJoystickSensibility(0.05);
  84916. this._rightjoystick.setJoystickColor("yellow");
  84917. };
  84918. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84919. this._leftjoystick.releaseCanvas();
  84920. this._rightjoystick.releaseCanvas();
  84921. };
  84922. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84923. return "FreeCameraVirtualJoystickInput";
  84924. };
  84925. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84926. return "virtualJoystick";
  84927. };
  84928. return FreeCameraVirtualJoystickInput;
  84929. }());
  84930. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84931. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84932. })(BABYLON || (BABYLON = {}));
  84933. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84934. "use strict";
  84935. var BABYLON;
  84936. (function (BABYLON) {
  84937. var SimplificationSettings = /** @class */ (function () {
  84938. function SimplificationSettings(quality, distance, optimizeMesh) {
  84939. this.quality = quality;
  84940. this.distance = distance;
  84941. this.optimizeMesh = optimizeMesh;
  84942. }
  84943. return SimplificationSettings;
  84944. }());
  84945. BABYLON.SimplificationSettings = SimplificationSettings;
  84946. var SimplificationQueue = /** @class */ (function () {
  84947. function SimplificationQueue() {
  84948. this.running = false;
  84949. this._simplificationArray = [];
  84950. }
  84951. SimplificationQueue.prototype.addTask = function (task) {
  84952. this._simplificationArray.push(task);
  84953. };
  84954. SimplificationQueue.prototype.executeNext = function () {
  84955. var task = this._simplificationArray.pop();
  84956. if (task) {
  84957. this.running = true;
  84958. this.runSimplification(task);
  84959. }
  84960. else {
  84961. this.running = false;
  84962. }
  84963. };
  84964. SimplificationQueue.prototype.runSimplification = function (task) {
  84965. var _this = this;
  84966. if (task.parallelProcessing) {
  84967. //parallel simplifier
  84968. task.settings.forEach(function (setting) {
  84969. var simplifier = _this.getSimplifier(task);
  84970. simplifier.simplify(setting, function (newMesh) {
  84971. task.mesh.addLODLevel(setting.distance, newMesh);
  84972. newMesh.isVisible = true;
  84973. //check if it is the last
  84974. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84975. //all done, run the success callback.
  84976. task.successCallback();
  84977. }
  84978. _this.executeNext();
  84979. });
  84980. });
  84981. }
  84982. else {
  84983. //single simplifier.
  84984. var simplifier = this.getSimplifier(task);
  84985. var runDecimation = function (setting, callback) {
  84986. simplifier.simplify(setting, function (newMesh) {
  84987. task.mesh.addLODLevel(setting.distance, newMesh);
  84988. newMesh.isVisible = true;
  84989. //run the next quality level
  84990. callback();
  84991. });
  84992. };
  84993. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84994. runDecimation(task.settings[loop.index], function () {
  84995. loop.executeNext();
  84996. });
  84997. }, function () {
  84998. //execution ended, run the success callback.
  84999. if (task.successCallback) {
  85000. task.successCallback();
  85001. }
  85002. _this.executeNext();
  85003. });
  85004. }
  85005. };
  85006. SimplificationQueue.prototype.getSimplifier = function (task) {
  85007. switch (task.simplificationType) {
  85008. case SimplificationType.QUADRATIC:
  85009. default:
  85010. return new QuadraticErrorSimplification(task.mesh);
  85011. }
  85012. };
  85013. return SimplificationQueue;
  85014. }());
  85015. BABYLON.SimplificationQueue = SimplificationQueue;
  85016. /**
  85017. * The implemented types of simplification.
  85018. * At the moment only Quadratic Error Decimation is implemented.
  85019. */
  85020. var SimplificationType;
  85021. (function (SimplificationType) {
  85022. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  85023. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  85024. var DecimationTriangle = /** @class */ (function () {
  85025. function DecimationTriangle(vertices) {
  85026. this.vertices = vertices;
  85027. this.error = new Array(4);
  85028. this.deleted = false;
  85029. this.isDirty = false;
  85030. this.deletePending = false;
  85031. this.borderFactor = 0;
  85032. }
  85033. return DecimationTriangle;
  85034. }());
  85035. BABYLON.DecimationTriangle = DecimationTriangle;
  85036. var DecimationVertex = /** @class */ (function () {
  85037. function DecimationVertex(position, id) {
  85038. this.position = position;
  85039. this.id = id;
  85040. this.isBorder = true;
  85041. this.q = new QuadraticMatrix();
  85042. this.triangleCount = 0;
  85043. this.triangleStart = 0;
  85044. this.originalOffsets = [];
  85045. }
  85046. DecimationVertex.prototype.updatePosition = function (newPosition) {
  85047. this.position.copyFrom(newPosition);
  85048. };
  85049. return DecimationVertex;
  85050. }());
  85051. BABYLON.DecimationVertex = DecimationVertex;
  85052. var QuadraticMatrix = /** @class */ (function () {
  85053. function QuadraticMatrix(data) {
  85054. this.data = new Array(10);
  85055. for (var i = 0; i < 10; ++i) {
  85056. if (data && data[i]) {
  85057. this.data[i] = data[i];
  85058. }
  85059. else {
  85060. this.data[i] = 0;
  85061. }
  85062. }
  85063. }
  85064. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  85065. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  85066. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  85067. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  85068. return det;
  85069. };
  85070. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  85071. for (var i = 0; i < 10; ++i) {
  85072. this.data[i] += matrix.data[i];
  85073. }
  85074. };
  85075. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  85076. for (var i = 0; i < 10; ++i) {
  85077. this.data[i] += data[i];
  85078. }
  85079. };
  85080. QuadraticMatrix.prototype.add = function (matrix) {
  85081. var m = new QuadraticMatrix();
  85082. for (var i = 0; i < 10; ++i) {
  85083. m.data[i] = this.data[i] + matrix.data[i];
  85084. }
  85085. return m;
  85086. };
  85087. QuadraticMatrix.FromData = function (a, b, c, d) {
  85088. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  85089. };
  85090. //returning an array to avoid garbage collection
  85091. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  85092. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  85093. };
  85094. return QuadraticMatrix;
  85095. }());
  85096. BABYLON.QuadraticMatrix = QuadraticMatrix;
  85097. var Reference = /** @class */ (function () {
  85098. function Reference(vertexId, triangleId) {
  85099. this.vertexId = vertexId;
  85100. this.triangleId = triangleId;
  85101. }
  85102. return Reference;
  85103. }());
  85104. BABYLON.Reference = Reference;
  85105. /**
  85106. * An implementation of the Quadratic Error simplification algorithm.
  85107. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  85108. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  85109. * @author RaananW
  85110. */
  85111. var QuadraticErrorSimplification = /** @class */ (function () {
  85112. function QuadraticErrorSimplification(_mesh) {
  85113. this._mesh = _mesh;
  85114. this.syncIterations = 5000;
  85115. this.aggressiveness = 7;
  85116. this.decimationIterations = 100;
  85117. this.boundingBoxEpsilon = BABYLON.Epsilon;
  85118. }
  85119. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  85120. var _this = this;
  85121. this.initDecimatedMesh();
  85122. //iterating through the submeshes array, one after the other.
  85123. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  85124. _this.initWithMesh(loop.index, function () {
  85125. _this.runDecimation(settings, loop.index, function () {
  85126. loop.executeNext();
  85127. });
  85128. }, settings.optimizeMesh);
  85129. }, function () {
  85130. setTimeout(function () {
  85131. successCallback(_this._reconstructedMesh);
  85132. }, 0);
  85133. });
  85134. };
  85135. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  85136. var _this = this;
  85137. var targetCount = ~~(this.triangles.length * settings.quality);
  85138. var deletedTriangles = 0;
  85139. var triangleCount = this.triangles.length;
  85140. var iterationFunction = function (iteration, callback) {
  85141. setTimeout(function () {
  85142. if (iteration % 5 === 0) {
  85143. _this.updateMesh(iteration === 0);
  85144. }
  85145. for (var i = 0; i < _this.triangles.length; ++i) {
  85146. _this.triangles[i].isDirty = false;
  85147. }
  85148. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  85149. var trianglesIterator = function (i) {
  85150. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  85151. var t = _this.triangles[tIdx];
  85152. if (!t)
  85153. return;
  85154. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  85155. return;
  85156. }
  85157. for (var j = 0; j < 3; ++j) {
  85158. if (t.error[j] < threshold) {
  85159. var deleted0 = [];
  85160. var deleted1 = [];
  85161. var v0 = t.vertices[j];
  85162. var v1 = t.vertices[(j + 1) % 3];
  85163. if (v0.isBorder || v1.isBorder)
  85164. continue;
  85165. var p = BABYLON.Vector3.Zero();
  85166. var n = BABYLON.Vector3.Zero();
  85167. var uv = BABYLON.Vector2.Zero();
  85168. var color = new BABYLON.Color4(0, 0, 0, 1);
  85169. _this.calculateError(v0, v1, p, n, uv, color);
  85170. var delTr = new Array();
  85171. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  85172. continue;
  85173. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  85174. continue;
  85175. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  85176. continue;
  85177. var uniqueArray = new Array();
  85178. delTr.forEach(function (deletedT) {
  85179. if (uniqueArray.indexOf(deletedT) === -1) {
  85180. deletedT.deletePending = true;
  85181. uniqueArray.push(deletedT);
  85182. }
  85183. });
  85184. if (uniqueArray.length % 2 !== 0) {
  85185. continue;
  85186. }
  85187. v0.q = v1.q.add(v0.q);
  85188. v0.updatePosition(p);
  85189. var tStart = _this.references.length;
  85190. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  85191. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  85192. var tCount = _this.references.length - tStart;
  85193. if (tCount <= v0.triangleCount) {
  85194. if (tCount) {
  85195. for (var c = 0; c < tCount; c++) {
  85196. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  85197. }
  85198. }
  85199. }
  85200. else {
  85201. v0.triangleStart = tStart;
  85202. }
  85203. v0.triangleCount = tCount;
  85204. break;
  85205. }
  85206. }
  85207. };
  85208. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  85209. }, 0);
  85210. };
  85211. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  85212. if (triangleCount - deletedTriangles <= targetCount)
  85213. loop.breakLoop();
  85214. else {
  85215. iterationFunction(loop.index, function () {
  85216. loop.executeNext();
  85217. });
  85218. }
  85219. }, function () {
  85220. setTimeout(function () {
  85221. //reconstruct this part of the mesh
  85222. _this.reconstructMesh(submeshIndex);
  85223. successCallback();
  85224. }, 0);
  85225. });
  85226. };
  85227. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  85228. var _this = this;
  85229. this.vertices = [];
  85230. this.triangles = [];
  85231. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85232. var indices = this._mesh.getIndices();
  85233. var submesh = this._mesh.subMeshes[submeshIndex];
  85234. var findInVertices = function (positionToSearch) {
  85235. if (optimizeMesh) {
  85236. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  85237. if (_this.vertices[ii].position.equals(positionToSearch)) {
  85238. return _this.vertices[ii];
  85239. }
  85240. }
  85241. }
  85242. return null;
  85243. };
  85244. var vertexReferences = [];
  85245. var vertexInit = function (i) {
  85246. if (!positionData) {
  85247. return;
  85248. }
  85249. var offset = i + submesh.verticesStart;
  85250. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  85251. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  85252. vertex.originalOffsets.push(offset);
  85253. if (vertex.id === _this.vertices.length) {
  85254. _this.vertices.push(vertex);
  85255. }
  85256. vertexReferences.push(vertex.id);
  85257. };
  85258. //var totalVertices = mesh.getTotalVertices();
  85259. var totalVertices = submesh.verticesCount;
  85260. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  85261. var indicesInit = function (i) {
  85262. if (!indices) {
  85263. return;
  85264. }
  85265. var offset = (submesh.indexStart / 3) + i;
  85266. var pos = (offset * 3);
  85267. var i0 = indices[pos + 0];
  85268. var i1 = indices[pos + 1];
  85269. var i2 = indices[pos + 2];
  85270. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  85271. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  85272. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  85273. var triangle = new DecimationTriangle([v0, v1, v2]);
  85274. triangle.originalOffset = pos;
  85275. _this.triangles.push(triangle);
  85276. };
  85277. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  85278. _this.init(callback);
  85279. });
  85280. });
  85281. };
  85282. QuadraticErrorSimplification.prototype.init = function (callback) {
  85283. var _this = this;
  85284. var triangleInit1 = function (i) {
  85285. var t = _this.triangles[i];
  85286. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  85287. for (var j = 0; j < 3; j++) {
  85288. 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))));
  85289. }
  85290. };
  85291. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  85292. var triangleInit2 = function (i) {
  85293. var t = _this.triangles[i];
  85294. for (var j = 0; j < 3; ++j) {
  85295. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  85296. }
  85297. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85298. };
  85299. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  85300. callback();
  85301. });
  85302. });
  85303. };
  85304. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  85305. var newTriangles = [];
  85306. var i;
  85307. for (i = 0; i < this.vertices.length; ++i) {
  85308. this.vertices[i].triangleCount = 0;
  85309. }
  85310. var t;
  85311. var j;
  85312. for (i = 0; i < this.triangles.length; ++i) {
  85313. if (!this.triangles[i].deleted) {
  85314. t = this.triangles[i];
  85315. for (j = 0; j < 3; ++j) {
  85316. t.vertices[j].triangleCount = 1;
  85317. }
  85318. newTriangles.push(t);
  85319. }
  85320. }
  85321. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  85322. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  85323. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  85324. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  85325. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  85326. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85327. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  85328. var vertexCount = 0;
  85329. for (i = 0; i < this.vertices.length; ++i) {
  85330. var vertex = this.vertices[i];
  85331. vertex.id = vertexCount;
  85332. if (vertex.triangleCount) {
  85333. vertex.originalOffsets.forEach(function (originalOffset) {
  85334. if (!normalData) {
  85335. return;
  85336. }
  85337. newPositionData.push(vertex.position.x);
  85338. newPositionData.push(vertex.position.y);
  85339. newPositionData.push(vertex.position.z);
  85340. newNormalData.push(normalData[originalOffset * 3]);
  85341. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  85342. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  85343. if (uvs && uvs.length) {
  85344. newUVsData.push(uvs[(originalOffset * 2)]);
  85345. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85346. }
  85347. else if (colorsData && colorsData.length) {
  85348. newColorsData.push(colorsData[(originalOffset * 4)]);
  85349. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85350. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85351. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85352. }
  85353. ++vertexCount;
  85354. });
  85355. }
  85356. }
  85357. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85358. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85359. var submeshesArray = this._reconstructedMesh.subMeshes;
  85360. this._reconstructedMesh.subMeshes = [];
  85361. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85362. var originalIndices = this._mesh.getIndices();
  85363. for (i = 0; i < newTriangles.length; ++i) {
  85364. t = newTriangles[i]; //now get the new referencing point for each vertex
  85365. [0, 1, 2].forEach(function (idx) {
  85366. var id = originalIndices[t.originalOffset + idx];
  85367. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85368. if (offset < 0)
  85369. offset = 0;
  85370. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85371. });
  85372. }
  85373. //overwriting the old vertex buffers and indices.
  85374. this._reconstructedMesh.setIndices(newIndicesArray);
  85375. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85376. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85377. if (newUVsData.length > 0)
  85378. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85379. if (newColorsData.length > 0)
  85380. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85381. //create submesh
  85382. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85383. if (submeshIndex > 0) {
  85384. this._reconstructedMesh.subMeshes = [];
  85385. submeshesArray.forEach(function (submesh) {
  85386. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85387. });
  85388. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85389. }
  85390. };
  85391. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85392. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85393. this._reconstructedMesh.material = this._mesh.material;
  85394. this._reconstructedMesh.parent = this._mesh.parent;
  85395. this._reconstructedMesh.isVisible = false;
  85396. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85397. };
  85398. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85399. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85400. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85401. if (t.deleted)
  85402. continue;
  85403. var s = this.references[vertex1.triangleStart + i].vertexId;
  85404. var v1 = t.vertices[(s + 1) % 3];
  85405. var v2 = t.vertices[(s + 2) % 3];
  85406. if ((v1 === vertex2 || v2 === vertex2)) {
  85407. deletedArray[i] = true;
  85408. delTr.push(t);
  85409. continue;
  85410. }
  85411. var d1 = v1.position.subtract(point);
  85412. d1 = d1.normalize();
  85413. var d2 = v2.position.subtract(point);
  85414. d2 = d2.normalize();
  85415. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85416. return true;
  85417. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85418. deletedArray[i] = false;
  85419. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85420. return true;
  85421. }
  85422. return false;
  85423. };
  85424. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85425. var newDeleted = deletedTriangles;
  85426. for (var i = 0; i < vertex.triangleCount; ++i) {
  85427. var ref = this.references[vertex.triangleStart + i];
  85428. var t = this.triangles[ref.triangleId];
  85429. if (t.deleted)
  85430. continue;
  85431. if (deletedArray[i] && t.deletePending) {
  85432. t.deleted = true;
  85433. newDeleted++;
  85434. continue;
  85435. }
  85436. t.vertices[ref.vertexId] = origVertex;
  85437. t.isDirty = true;
  85438. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85439. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85440. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85441. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85442. this.references.push(ref);
  85443. }
  85444. return newDeleted;
  85445. };
  85446. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85447. for (var i = 0; i < this.vertices.length; ++i) {
  85448. var vCount = [];
  85449. var vId = [];
  85450. var v = this.vertices[i];
  85451. var j;
  85452. for (j = 0; j < v.triangleCount; ++j) {
  85453. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85454. for (var ii = 0; ii < 3; ii++) {
  85455. var ofs = 0;
  85456. var vv = triangle.vertices[ii];
  85457. while (ofs < vCount.length) {
  85458. if (vId[ofs] === vv.id)
  85459. break;
  85460. ++ofs;
  85461. }
  85462. if (ofs === vCount.length) {
  85463. vCount.push(1);
  85464. vId.push(vv.id);
  85465. }
  85466. else {
  85467. vCount[ofs]++;
  85468. }
  85469. }
  85470. }
  85471. for (j = 0; j < vCount.length; ++j) {
  85472. if (vCount[j] === 1) {
  85473. this.vertices[vId[j]].isBorder = true;
  85474. }
  85475. else {
  85476. this.vertices[vId[j]].isBorder = false;
  85477. }
  85478. }
  85479. }
  85480. };
  85481. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85482. if (identifyBorders === void 0) { identifyBorders = false; }
  85483. var i;
  85484. if (!identifyBorders) {
  85485. var newTrianglesVector = [];
  85486. for (i = 0; i < this.triangles.length; ++i) {
  85487. if (!this.triangles[i].deleted) {
  85488. newTrianglesVector.push(this.triangles[i]);
  85489. }
  85490. }
  85491. this.triangles = newTrianglesVector;
  85492. }
  85493. for (i = 0; i < this.vertices.length; ++i) {
  85494. this.vertices[i].triangleCount = 0;
  85495. this.vertices[i].triangleStart = 0;
  85496. }
  85497. var t;
  85498. var j;
  85499. var v;
  85500. for (i = 0; i < this.triangles.length; ++i) {
  85501. t = this.triangles[i];
  85502. for (j = 0; j < 3; ++j) {
  85503. v = t.vertices[j];
  85504. v.triangleCount++;
  85505. }
  85506. }
  85507. var tStart = 0;
  85508. for (i = 0; i < this.vertices.length; ++i) {
  85509. this.vertices[i].triangleStart = tStart;
  85510. tStart += this.vertices[i].triangleCount;
  85511. this.vertices[i].triangleCount = 0;
  85512. }
  85513. var newReferences = new Array(this.triangles.length * 3);
  85514. for (i = 0; i < this.triangles.length; ++i) {
  85515. t = this.triangles[i];
  85516. for (j = 0; j < 3; ++j) {
  85517. v = t.vertices[j];
  85518. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85519. v.triangleCount++;
  85520. }
  85521. }
  85522. this.references = newReferences;
  85523. if (identifyBorders) {
  85524. this.identifyBorder();
  85525. }
  85526. };
  85527. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85528. var x = point.x;
  85529. var y = point.y;
  85530. var z = point.z;
  85531. 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
  85532. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85533. };
  85534. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85535. var q = vertex1.q.add(vertex2.q);
  85536. var border = vertex1.isBorder && vertex2.isBorder;
  85537. var error = 0;
  85538. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85539. if (qDet !== 0 && !border) {
  85540. if (!pointResult) {
  85541. pointResult = BABYLON.Vector3.Zero();
  85542. }
  85543. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85544. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85545. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85546. error = this.vertexError(q, pointResult);
  85547. }
  85548. else {
  85549. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85550. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85551. var error1 = this.vertexError(q, vertex1.position);
  85552. var error2 = this.vertexError(q, vertex2.position);
  85553. var error3 = this.vertexError(q, p3);
  85554. error = Math.min(error1, error2, error3);
  85555. if (error === error1) {
  85556. if (pointResult) {
  85557. pointResult.copyFrom(vertex1.position);
  85558. }
  85559. }
  85560. else if (error === error2) {
  85561. if (pointResult) {
  85562. pointResult.copyFrom(vertex2.position);
  85563. }
  85564. }
  85565. else {
  85566. if (pointResult) {
  85567. pointResult.copyFrom(p3);
  85568. }
  85569. }
  85570. }
  85571. return error;
  85572. };
  85573. return QuadraticErrorSimplification;
  85574. }());
  85575. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85576. })(BABYLON || (BABYLON = {}));
  85577. //# sourceMappingURL=babylon.meshSimplification.js.map
  85578. "use strict";
  85579. var BABYLON;
  85580. (function (BABYLON) {
  85581. var MeshLODLevel = /** @class */ (function () {
  85582. function MeshLODLevel(distance, mesh) {
  85583. this.distance = distance;
  85584. this.mesh = mesh;
  85585. }
  85586. return MeshLODLevel;
  85587. }());
  85588. BABYLON.MeshLODLevel = MeshLODLevel;
  85589. })(BABYLON || (BABYLON = {}));
  85590. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85591. "use strict";
  85592. var BABYLON;
  85593. (function (BABYLON) {
  85594. /**
  85595. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85596. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85597. */
  85598. var SceneOptimization = /** @class */ (function () {
  85599. /**
  85600. * Creates the SceneOptimization object
  85601. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85602. * @param desc defines the description associated with the optimization
  85603. */
  85604. function SceneOptimization(
  85605. /**
  85606. * Defines the priority of this optimization (0 by default which means first in the list)
  85607. */
  85608. priority) {
  85609. if (priority === void 0) { priority = 0; }
  85610. this.priority = priority;
  85611. }
  85612. /**
  85613. * Gets a string describing the action executed by the current optimization
  85614. * @returns description string
  85615. */
  85616. SceneOptimization.prototype.getDescription = function () {
  85617. return "";
  85618. };
  85619. /**
  85620. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85621. * @param scene defines the current scene where to apply this optimization
  85622. * @param optimizer defines the current optimizer
  85623. * @returns true if everything that can be done was applied
  85624. */
  85625. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85626. return true;
  85627. };
  85628. ;
  85629. return SceneOptimization;
  85630. }());
  85631. BABYLON.SceneOptimization = SceneOptimization;
  85632. /**
  85633. * Defines an optimization used to reduce the size of render target textures
  85634. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85635. */
  85636. var TextureOptimization = /** @class */ (function (_super) {
  85637. __extends(TextureOptimization, _super);
  85638. /**
  85639. * Creates the TextureOptimization object
  85640. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85641. * @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
  85642. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85643. */
  85644. function TextureOptimization(
  85645. /**
  85646. * Defines the priority of this optimization (0 by default which means first in the list)
  85647. */
  85648. priority,
  85649. /**
  85650. * 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
  85651. */
  85652. maximumSize,
  85653. /**
  85654. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85655. */
  85656. step) {
  85657. if (priority === void 0) { priority = 0; }
  85658. if (maximumSize === void 0) { maximumSize = 1024; }
  85659. if (step === void 0) { step = 0.5; }
  85660. var _this = _super.call(this, priority) || this;
  85661. _this.priority = priority;
  85662. _this.maximumSize = maximumSize;
  85663. _this.step = step;
  85664. return _this;
  85665. }
  85666. /**
  85667. * Gets a string describing the action executed by the current optimization
  85668. * @returns description string
  85669. */
  85670. TextureOptimization.prototype.getDescription = function () {
  85671. return "Reducing render target texture size to " + this.maximumSize;
  85672. };
  85673. /**
  85674. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85675. * @param scene defines the current scene where to apply this optimization
  85676. * @param optimizer defines the current optimizer
  85677. * @returns true if everything that can be done was applied
  85678. */
  85679. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85680. var allDone = true;
  85681. for (var index = 0; index < scene.textures.length; index++) {
  85682. var texture = scene.textures[index];
  85683. if (!texture.canRescale || texture.getContext) {
  85684. continue;
  85685. }
  85686. var currentSize = texture.getSize();
  85687. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85688. if (maxDimension > this.maximumSize) {
  85689. texture.scale(this.step);
  85690. allDone = false;
  85691. }
  85692. }
  85693. return allDone;
  85694. };
  85695. return TextureOptimization;
  85696. }(SceneOptimization));
  85697. BABYLON.TextureOptimization = TextureOptimization;
  85698. /**
  85699. * Defines an optimization used to increase or decrease the rendering resolution
  85700. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85701. */
  85702. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85703. __extends(HardwareScalingOptimization, _super);
  85704. /**
  85705. * Creates the HardwareScalingOptimization object
  85706. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85707. * @param maximumScale defines the maximum scale to use (2 by default)
  85708. * @param step defines the step to use between two passes (0.5 by default)
  85709. */
  85710. function HardwareScalingOptimization(
  85711. /**
  85712. * Defines the priority of this optimization (0 by default which means first in the list)
  85713. */
  85714. priority,
  85715. /**
  85716. * Defines the maximum scale to use (2 by default)
  85717. */
  85718. maximumScale,
  85719. /**
  85720. * Defines the step to use between two passes (0.5 by default)
  85721. */
  85722. step) {
  85723. if (priority === void 0) { priority = 0; }
  85724. if (maximumScale === void 0) { maximumScale = 2; }
  85725. if (step === void 0) { step = 0.25; }
  85726. var _this = _super.call(this, priority) || this;
  85727. _this.priority = priority;
  85728. _this.maximumScale = maximumScale;
  85729. _this.step = step;
  85730. _this._currentScale = -1;
  85731. _this._directionOffset = 1;
  85732. return _this;
  85733. }
  85734. /**
  85735. * Gets a string describing the action executed by the current optimization
  85736. * @return description string
  85737. */
  85738. HardwareScalingOptimization.prototype.getDescription = function () {
  85739. return "Setting hardware scaling level to " + this._currentScale;
  85740. };
  85741. /**
  85742. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85743. * @param scene defines the current scene where to apply this optimization
  85744. * @param optimizer defines the current optimizer
  85745. * @returns true if everything that can be done was applied
  85746. */
  85747. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85748. if (this._currentScale === -1) {
  85749. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85750. if (this._currentScale > this.maximumScale) {
  85751. this._directionOffset = -1;
  85752. }
  85753. }
  85754. this._currentScale += this._directionOffset * this.step;
  85755. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85756. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85757. };
  85758. ;
  85759. return HardwareScalingOptimization;
  85760. }(SceneOptimization));
  85761. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85762. /**
  85763. * Defines an optimization used to remove shadows
  85764. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85765. */
  85766. var ShadowsOptimization = /** @class */ (function (_super) {
  85767. __extends(ShadowsOptimization, _super);
  85768. function ShadowsOptimization() {
  85769. return _super !== null && _super.apply(this, arguments) || this;
  85770. }
  85771. /**
  85772. * Gets a string describing the action executed by the current optimization
  85773. * @return description string
  85774. */
  85775. ShadowsOptimization.prototype.getDescription = function () {
  85776. return "Turning shadows on/off";
  85777. };
  85778. /**
  85779. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85780. * @param scene defines the current scene where to apply this optimization
  85781. * @param optimizer defines the current optimizer
  85782. * @returns true if everything that can be done was applied
  85783. */
  85784. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85785. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85786. return true;
  85787. };
  85788. ;
  85789. return ShadowsOptimization;
  85790. }(SceneOptimization));
  85791. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85792. /**
  85793. * Defines an optimization used to turn post-processes off
  85794. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85795. */
  85796. var PostProcessesOptimization = /** @class */ (function (_super) {
  85797. __extends(PostProcessesOptimization, _super);
  85798. function PostProcessesOptimization() {
  85799. return _super !== null && _super.apply(this, arguments) || this;
  85800. }
  85801. /**
  85802. * Gets a string describing the action executed by the current optimization
  85803. * @return description string
  85804. */
  85805. PostProcessesOptimization.prototype.getDescription = function () {
  85806. return "Turning post-processes on/off";
  85807. };
  85808. /**
  85809. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85810. * @param scene defines the current scene where to apply this optimization
  85811. * @param optimizer defines the current optimizer
  85812. * @returns true if everything that can be done was applied
  85813. */
  85814. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85815. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85816. return true;
  85817. };
  85818. ;
  85819. return PostProcessesOptimization;
  85820. }(SceneOptimization));
  85821. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85822. /**
  85823. * Defines an optimization used to turn lens flares off
  85824. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85825. */
  85826. var LensFlaresOptimization = /** @class */ (function (_super) {
  85827. __extends(LensFlaresOptimization, _super);
  85828. function LensFlaresOptimization() {
  85829. return _super !== null && _super.apply(this, arguments) || this;
  85830. }
  85831. /**
  85832. * Gets a string describing the action executed by the current optimization
  85833. * @return description string
  85834. */
  85835. LensFlaresOptimization.prototype.getDescription = function () {
  85836. return "Turning lens flares on/off";
  85837. };
  85838. /**
  85839. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85840. * @param scene defines the current scene where to apply this optimization
  85841. * @param optimizer defines the current optimizer
  85842. * @returns true if everything that can be done was applied
  85843. */
  85844. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85845. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85846. return true;
  85847. };
  85848. ;
  85849. return LensFlaresOptimization;
  85850. }(SceneOptimization));
  85851. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85852. /**
  85853. * Defines an optimization based on user defined callback.
  85854. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85855. */
  85856. var CustomOptimization = /** @class */ (function (_super) {
  85857. __extends(CustomOptimization, _super);
  85858. function CustomOptimization() {
  85859. return _super !== null && _super.apply(this, arguments) || this;
  85860. }
  85861. /**
  85862. * Gets a string describing the action executed by the current optimization
  85863. * @returns description string
  85864. */
  85865. CustomOptimization.prototype.getDescription = function () {
  85866. if (this.onGetDescription) {
  85867. return this.onGetDescription();
  85868. }
  85869. return "Running user defined callback";
  85870. };
  85871. /**
  85872. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85873. * @param scene defines the current scene where to apply this optimization
  85874. * @param optimizer defines the current optimizer
  85875. * @returns true if everything that can be done was applied
  85876. */
  85877. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85878. if (this.onApply) {
  85879. return this.onApply(scene, optimizer);
  85880. }
  85881. return true;
  85882. };
  85883. ;
  85884. return CustomOptimization;
  85885. }(SceneOptimization));
  85886. BABYLON.CustomOptimization = CustomOptimization;
  85887. /**
  85888. * Defines an optimization used to turn particles off
  85889. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85890. */
  85891. var ParticlesOptimization = /** @class */ (function (_super) {
  85892. __extends(ParticlesOptimization, _super);
  85893. function ParticlesOptimization() {
  85894. return _super !== null && _super.apply(this, arguments) || this;
  85895. }
  85896. /**
  85897. * Gets a string describing the action executed by the current optimization
  85898. * @return description string
  85899. */
  85900. ParticlesOptimization.prototype.getDescription = function () {
  85901. return "Turning particles on/off";
  85902. };
  85903. /**
  85904. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85905. * @param scene defines the current scene where to apply this optimization
  85906. * @param optimizer defines the current optimizer
  85907. * @returns true if everything that can be done was applied
  85908. */
  85909. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85910. scene.particlesEnabled = optimizer.isInImprovementMode;
  85911. return true;
  85912. };
  85913. ;
  85914. return ParticlesOptimization;
  85915. }(SceneOptimization));
  85916. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85917. /**
  85918. * Defines an optimization used to turn render targets off
  85919. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85920. */
  85921. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85922. __extends(RenderTargetsOptimization, _super);
  85923. function RenderTargetsOptimization() {
  85924. return _super !== null && _super.apply(this, arguments) || this;
  85925. }
  85926. /**
  85927. * Gets a string describing the action executed by the current optimization
  85928. * @return description string
  85929. */
  85930. RenderTargetsOptimization.prototype.getDescription = function () {
  85931. return "Turning render targets off";
  85932. };
  85933. /**
  85934. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85935. * @param scene defines the current scene where to apply this optimization
  85936. * @param optimizer defines the current optimizer
  85937. * @returns true if everything that can be done was applied
  85938. */
  85939. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85940. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85941. return true;
  85942. };
  85943. ;
  85944. return RenderTargetsOptimization;
  85945. }(SceneOptimization));
  85946. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85947. /**
  85948. * Defines an optimization used to merge meshes with compatible materials
  85949. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85950. */
  85951. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85952. __extends(MergeMeshesOptimization, _super);
  85953. function MergeMeshesOptimization() {
  85954. var _this = _super !== null && _super.apply(this, arguments) || this;
  85955. _this._canBeMerged = function (abstractMesh) {
  85956. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85957. return false;
  85958. }
  85959. var mesh = abstractMesh;
  85960. if (!mesh.isVisible || !mesh.isEnabled()) {
  85961. return false;
  85962. }
  85963. if (mesh.instances.length > 0) {
  85964. return false;
  85965. }
  85966. if (mesh.skeleton || mesh.hasLODLevels) {
  85967. return false;
  85968. }
  85969. if (mesh.parent) {
  85970. return false;
  85971. }
  85972. return true;
  85973. };
  85974. return _this;
  85975. }
  85976. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85977. /**
  85978. * Gets or sets a boolean which defines if optimization octree has to be updated
  85979. */
  85980. get: function () {
  85981. return MergeMeshesOptimization._UpdateSelectionTree;
  85982. },
  85983. /**
  85984. * Gets or sets a boolean which defines if optimization octree has to be updated
  85985. */
  85986. set: function (value) {
  85987. MergeMeshesOptimization._UpdateSelectionTree = value;
  85988. },
  85989. enumerable: true,
  85990. configurable: true
  85991. });
  85992. /**
  85993. * Gets a string describing the action executed by the current optimization
  85994. * @return description string
  85995. */
  85996. MergeMeshesOptimization.prototype.getDescription = function () {
  85997. return "Merging similar meshes together";
  85998. };
  85999. /**
  86000. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  86001. * @param scene defines the current scene where to apply this optimization
  86002. * @param optimizer defines the current optimizer
  86003. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  86004. * @returns true if everything that can be done was applied
  86005. */
  86006. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  86007. var globalPool = scene.meshes.slice(0);
  86008. var globalLength = globalPool.length;
  86009. for (var index = 0; index < globalLength; index++) {
  86010. var currentPool = new Array();
  86011. var current = globalPool[index];
  86012. // Checks
  86013. if (!this._canBeMerged(current)) {
  86014. continue;
  86015. }
  86016. currentPool.push(current);
  86017. // Find compatible meshes
  86018. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  86019. var otherMesh = globalPool[subIndex];
  86020. if (!this._canBeMerged(otherMesh)) {
  86021. continue;
  86022. }
  86023. if (otherMesh.material !== current.material) {
  86024. continue;
  86025. }
  86026. if (otherMesh.checkCollisions !== current.checkCollisions) {
  86027. continue;
  86028. }
  86029. currentPool.push(otherMesh);
  86030. globalLength--;
  86031. globalPool.splice(subIndex, 1);
  86032. subIndex--;
  86033. }
  86034. if (currentPool.length < 2) {
  86035. continue;
  86036. }
  86037. // Merge meshes
  86038. BABYLON.Mesh.MergeMeshes(currentPool);
  86039. }
  86040. if (updateSelectionTree != undefined) {
  86041. if (updateSelectionTree) {
  86042. scene.createOrUpdateSelectionOctree();
  86043. }
  86044. }
  86045. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  86046. scene.createOrUpdateSelectionOctree();
  86047. }
  86048. return true;
  86049. };
  86050. ;
  86051. MergeMeshesOptimization._UpdateSelectionTree = false;
  86052. return MergeMeshesOptimization;
  86053. }(SceneOptimization));
  86054. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  86055. /**
  86056. * Defines a list of options used by SceneOptimizer
  86057. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86058. */
  86059. var SceneOptimizerOptions = /** @class */ (function () {
  86060. /**
  86061. * Creates a new list of options used by SceneOptimizer
  86062. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  86063. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  86064. */
  86065. function SceneOptimizerOptions(
  86066. /**
  86067. * Defines the target frame rate to reach (60 by default)
  86068. */
  86069. targetFrameRate,
  86070. /**
  86071. * Defines the interval between two checkes (2000ms by default)
  86072. */
  86073. trackerDuration) {
  86074. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  86075. if (trackerDuration === void 0) { trackerDuration = 2000; }
  86076. this.targetFrameRate = targetFrameRate;
  86077. this.trackerDuration = trackerDuration;
  86078. /**
  86079. * Gets the list of optimizations to apply
  86080. */
  86081. this.optimizations = new Array();
  86082. }
  86083. /**
  86084. * Add a new optimization
  86085. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  86086. * @returns the current SceneOptimizerOptions
  86087. */
  86088. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  86089. this.optimizations.push(optimization);
  86090. return this;
  86091. };
  86092. /**
  86093. * Add a new custom optimization
  86094. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  86095. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  86096. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  86097. * @returns the current SceneOptimizerOptions
  86098. */
  86099. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  86100. if (priority === void 0) { priority = 0; }
  86101. var optimization = new CustomOptimization(priority);
  86102. optimization.onApply = onApply;
  86103. optimization.onGetDescription = onGetDescription;
  86104. this.optimizations.push(optimization);
  86105. return this;
  86106. };
  86107. /**
  86108. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  86109. * @param targetFrameRate defines the target frame rate (60 by default)
  86110. * @returns a SceneOptimizerOptions object
  86111. */
  86112. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  86113. var result = new SceneOptimizerOptions(targetFrameRate);
  86114. var priority = 0;
  86115. result.addOptimization(new MergeMeshesOptimization(priority));
  86116. result.addOptimization(new ShadowsOptimization(priority));
  86117. result.addOptimization(new LensFlaresOptimization(priority));
  86118. // Next priority
  86119. priority++;
  86120. result.addOptimization(new PostProcessesOptimization(priority));
  86121. result.addOptimization(new ParticlesOptimization(priority));
  86122. // Next priority
  86123. priority++;
  86124. result.addOptimization(new TextureOptimization(priority, 1024));
  86125. return result;
  86126. };
  86127. /**
  86128. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  86129. * @param targetFrameRate defines the target frame rate (60 by default)
  86130. * @returns a SceneOptimizerOptions object
  86131. */
  86132. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  86133. var result = new SceneOptimizerOptions(targetFrameRate);
  86134. var priority = 0;
  86135. result.addOptimization(new MergeMeshesOptimization(priority));
  86136. result.addOptimization(new ShadowsOptimization(priority));
  86137. result.addOptimization(new LensFlaresOptimization(priority));
  86138. // Next priority
  86139. priority++;
  86140. result.addOptimization(new PostProcessesOptimization(priority));
  86141. result.addOptimization(new ParticlesOptimization(priority));
  86142. // Next priority
  86143. priority++;
  86144. result.addOptimization(new TextureOptimization(priority, 512));
  86145. // Next priority
  86146. priority++;
  86147. result.addOptimization(new RenderTargetsOptimization(priority));
  86148. // Next priority
  86149. priority++;
  86150. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  86151. return result;
  86152. };
  86153. /**
  86154. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  86155. * @param targetFrameRate defines the target frame rate (60 by default)
  86156. * @returns a SceneOptimizerOptions object
  86157. */
  86158. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  86159. var result = new SceneOptimizerOptions(targetFrameRate);
  86160. var priority = 0;
  86161. result.addOptimization(new MergeMeshesOptimization(priority));
  86162. result.addOptimization(new ShadowsOptimization(priority));
  86163. result.addOptimization(new LensFlaresOptimization(priority));
  86164. // Next priority
  86165. priority++;
  86166. result.addOptimization(new PostProcessesOptimization(priority));
  86167. result.addOptimization(new ParticlesOptimization(priority));
  86168. // Next priority
  86169. priority++;
  86170. result.addOptimization(new TextureOptimization(priority, 256));
  86171. // Next priority
  86172. priority++;
  86173. result.addOptimization(new RenderTargetsOptimization(priority));
  86174. // Next priority
  86175. priority++;
  86176. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  86177. return result;
  86178. };
  86179. return SceneOptimizerOptions;
  86180. }());
  86181. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  86182. /**
  86183. * Class used to run optimizations in order to reach a target frame rate
  86184. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86185. */
  86186. var SceneOptimizer = /** @class */ (function () {
  86187. /**
  86188. * Creates a new SceneOptimizer
  86189. * @param scene defines the scene to work on
  86190. * @param options defines the options to use with the SceneOptimizer
  86191. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  86192. * @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)
  86193. */
  86194. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  86195. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  86196. if (improvementMode === void 0) { improvementMode = false; }
  86197. var _this = this;
  86198. this._isRunning = false;
  86199. this._currentPriorityLevel = 0;
  86200. this._targetFrameRate = 60;
  86201. this._trackerDuration = 2000;
  86202. this._currentFrameRate = 0;
  86203. this._improvementMode = false;
  86204. /**
  86205. * Defines an observable called when the optimizer reaches the target frame rate
  86206. */
  86207. this.onSuccessObservable = new BABYLON.Observable();
  86208. /**
  86209. * Defines an observable called when the optimizer enables an optimization
  86210. */
  86211. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  86212. /**
  86213. * Defines an observable called when the optimizer is not able to reach the target frame rate
  86214. */
  86215. this.onFailureObservable = new BABYLON.Observable();
  86216. if (!options) {
  86217. this._options = new SceneOptimizerOptions();
  86218. }
  86219. else {
  86220. this._options = options;
  86221. }
  86222. if (this._options.targetFrameRate) {
  86223. this._targetFrameRate = this._options.targetFrameRate;
  86224. }
  86225. if (this._options.trackerDuration) {
  86226. this._trackerDuration = this._options.trackerDuration;
  86227. }
  86228. if (autoGeneratePriorities) {
  86229. var priority = 0;
  86230. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  86231. var optim = _a[_i];
  86232. optim.priority = priority++;
  86233. }
  86234. }
  86235. this._improvementMode = improvementMode;
  86236. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86237. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  86238. _this._sceneDisposeObserver = null;
  86239. _this.dispose();
  86240. });
  86241. }
  86242. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  86243. /**
  86244. * Gets a boolean indicating if the optimizer is in improvement mode
  86245. */
  86246. get: function () {
  86247. return this._improvementMode;
  86248. },
  86249. enumerable: true,
  86250. configurable: true
  86251. });
  86252. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  86253. /**
  86254. * Gets the current priority level (0 at start)
  86255. */
  86256. get: function () {
  86257. return this._currentPriorityLevel;
  86258. },
  86259. enumerable: true,
  86260. configurable: true
  86261. });
  86262. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  86263. /**
  86264. * Gets the current frame rate checked by the SceneOptimizer
  86265. */
  86266. get: function () {
  86267. return this._currentFrameRate;
  86268. },
  86269. enumerable: true,
  86270. configurable: true
  86271. });
  86272. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  86273. /**
  86274. * Gets or sets the current target frame rate (60 by default)
  86275. */
  86276. get: function () {
  86277. return this._targetFrameRate;
  86278. },
  86279. /**
  86280. * Gets or sets the current target frame rate (60 by default)
  86281. */
  86282. set: function (value) {
  86283. this._targetFrameRate = value;
  86284. },
  86285. enumerable: true,
  86286. configurable: true
  86287. });
  86288. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  86289. /**
  86290. * Gets or sets the current interval between two checks (every 2000ms by default)
  86291. */
  86292. get: function () {
  86293. return this._trackerDuration;
  86294. },
  86295. /**
  86296. * Gets or sets the current interval between two checks (every 2000ms by default)
  86297. */
  86298. set: function (value) {
  86299. this._trackerDuration = value;
  86300. },
  86301. enumerable: true,
  86302. configurable: true
  86303. });
  86304. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  86305. /**
  86306. * Gets the list of active optimizations
  86307. */
  86308. get: function () {
  86309. return this._options.optimizations;
  86310. },
  86311. enumerable: true,
  86312. configurable: true
  86313. });
  86314. /**
  86315. * Stops the current optimizer
  86316. */
  86317. SceneOptimizer.prototype.stop = function () {
  86318. this._isRunning = false;
  86319. };
  86320. /**
  86321. * Reset the optimizer to initial step (current priority level = 0)
  86322. */
  86323. SceneOptimizer.prototype.reset = function () {
  86324. this._currentPriorityLevel = 0;
  86325. };
  86326. /**
  86327. * Start the optimizer. By default it will try to reach a specific framerate
  86328. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  86329. */
  86330. SceneOptimizer.prototype.start = function () {
  86331. var _this = this;
  86332. if (this._isRunning) {
  86333. return;
  86334. }
  86335. this._isRunning = true;
  86336. // Let's wait for the scene to be ready before running our check
  86337. this._scene.executeWhenReady(function () {
  86338. setTimeout(function () {
  86339. _this._checkCurrentState();
  86340. }, _this._trackerDuration);
  86341. });
  86342. };
  86343. SceneOptimizer.prototype._checkCurrentState = function () {
  86344. var _this = this;
  86345. if (!this._isRunning) {
  86346. return;
  86347. }
  86348. var scene = this._scene;
  86349. var options = this._options;
  86350. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86351. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86352. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86353. this._isRunning = false;
  86354. this.onSuccessObservable.notifyObservers(this);
  86355. return;
  86356. }
  86357. // Apply current level of optimizations
  86358. var allDone = true;
  86359. var noOptimizationApplied = true;
  86360. for (var index = 0; index < options.optimizations.length; index++) {
  86361. var optimization = options.optimizations[index];
  86362. if (optimization.priority === this._currentPriorityLevel) {
  86363. noOptimizationApplied = false;
  86364. allDone = allDone && optimization.apply(scene, this);
  86365. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86366. }
  86367. }
  86368. // If no optimization was applied, this is a failure :(
  86369. if (noOptimizationApplied) {
  86370. this._isRunning = false;
  86371. this.onFailureObservable.notifyObservers(this);
  86372. return;
  86373. }
  86374. // If all optimizations were done, move to next level
  86375. if (allDone) {
  86376. this._currentPriorityLevel++;
  86377. }
  86378. // Let's the system running for a specific amount of time before checking FPS
  86379. scene.executeWhenReady(function () {
  86380. setTimeout(function () {
  86381. _this._checkCurrentState();
  86382. }, _this._trackerDuration);
  86383. });
  86384. };
  86385. /**
  86386. * Release all resources
  86387. */
  86388. SceneOptimizer.prototype.dispose = function () {
  86389. this.stop();
  86390. this.onSuccessObservable.clear();
  86391. this.onFailureObservable.clear();
  86392. this.onNewOptimizationAppliedObservable.clear();
  86393. if (this._sceneDisposeObserver) {
  86394. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86395. }
  86396. };
  86397. /**
  86398. * Helper function to create a SceneOptimizer with one single line of code
  86399. * @param scene defines the scene to work on
  86400. * @param options defines the options to use with the SceneOptimizer
  86401. * @param onSuccess defines a callback to call on success
  86402. * @param onFailure defines a callback to call on failure
  86403. * @returns the new SceneOptimizer object
  86404. */
  86405. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86406. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86407. if (onSuccess) {
  86408. optimizer.onSuccessObservable.add(function () {
  86409. onSuccess();
  86410. });
  86411. }
  86412. if (onFailure) {
  86413. optimizer.onFailureObservable.add(function () {
  86414. onFailure();
  86415. });
  86416. }
  86417. optimizer.start();
  86418. return optimizer;
  86419. };
  86420. return SceneOptimizer;
  86421. }());
  86422. BABYLON.SceneOptimizer = SceneOptimizer;
  86423. })(BABYLON || (BABYLON = {}));
  86424. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86425. "use strict";
  86426. var BABYLON;
  86427. (function (BABYLON) {
  86428. var OutlineRenderer = /** @class */ (function () {
  86429. function OutlineRenderer(scene) {
  86430. this.zOffset = 1;
  86431. this._scene = scene;
  86432. }
  86433. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86434. var _this = this;
  86435. if (useOverlay === void 0) { useOverlay = false; }
  86436. var scene = this._scene;
  86437. var engine = this._scene.getEngine();
  86438. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86439. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86440. return;
  86441. }
  86442. var mesh = subMesh.getRenderingMesh();
  86443. var material = subMesh.getMaterial();
  86444. if (!material || !scene.activeCamera) {
  86445. return;
  86446. }
  86447. engine.enableEffect(this._effect);
  86448. // Logarithmic depth
  86449. if (material.useLogarithmicDepth) {
  86450. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86451. }
  86452. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86453. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86454. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86455. // Bones
  86456. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86457. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86458. }
  86459. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86460. // Alpha test
  86461. if (material && material.needAlphaTesting()) {
  86462. var alphaTexture = material.getAlphaTestTexture();
  86463. if (alphaTexture) {
  86464. this._effect.setTexture("diffuseSampler", alphaTexture);
  86465. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86466. }
  86467. }
  86468. engine.setZOffset(-this.zOffset);
  86469. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86470. engine.setZOffset(0);
  86471. };
  86472. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86473. var defines = [];
  86474. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86475. var mesh = subMesh.getMesh();
  86476. var material = subMesh.getMaterial();
  86477. if (material) {
  86478. // Alpha test
  86479. if (material.needAlphaTesting()) {
  86480. defines.push("#define ALPHATEST");
  86481. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86482. attribs.push(BABYLON.VertexBuffer.UVKind);
  86483. defines.push("#define UV1");
  86484. }
  86485. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86486. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86487. defines.push("#define UV2");
  86488. }
  86489. }
  86490. //Logarithmic depth
  86491. if (material.useLogarithmicDepth) {
  86492. defines.push("#define LOGARITHMICDEPTH");
  86493. }
  86494. }
  86495. // Bones
  86496. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86497. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86498. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86499. if (mesh.numBoneInfluencers > 4) {
  86500. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86501. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86502. }
  86503. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86504. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86505. }
  86506. else {
  86507. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86508. }
  86509. // Instances
  86510. if (useInstances) {
  86511. defines.push("#define INSTANCES");
  86512. attribs.push("world0");
  86513. attribs.push("world1");
  86514. attribs.push("world2");
  86515. attribs.push("world3");
  86516. }
  86517. // Get correct effect
  86518. var join = defines.join("\n");
  86519. if (this._cachedDefines !== join) {
  86520. this._cachedDefines = join;
  86521. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86522. }
  86523. return this._effect.isReady();
  86524. };
  86525. return OutlineRenderer;
  86526. }());
  86527. BABYLON.OutlineRenderer = OutlineRenderer;
  86528. })(BABYLON || (BABYLON = {}));
  86529. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86530. "use strict";
  86531. var BABYLON;
  86532. (function (BABYLON) {
  86533. var FaceAdjacencies = /** @class */ (function () {
  86534. function FaceAdjacencies() {
  86535. this.edges = new Array();
  86536. this.edgesConnectedCount = 0;
  86537. }
  86538. return FaceAdjacencies;
  86539. }());
  86540. var EdgesRenderer = /** @class */ (function () {
  86541. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86542. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86543. if (epsilon === void 0) { epsilon = 0.95; }
  86544. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86545. this.edgesWidthScalerForOrthographic = 1000.0;
  86546. this.edgesWidthScalerForPerspective = 50.0;
  86547. this._linesPositions = new Array();
  86548. this._linesNormals = new Array();
  86549. this._linesIndices = new Array();
  86550. this._buffers = {};
  86551. this._checkVerticesInsteadOfIndices = false;
  86552. this._source = source;
  86553. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86554. this._epsilon = epsilon;
  86555. this._prepareRessources();
  86556. this._generateEdgesLines();
  86557. }
  86558. EdgesRenderer.prototype._prepareRessources = function () {
  86559. if (this._lineShader) {
  86560. return;
  86561. }
  86562. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86563. attributes: ["position", "normal"],
  86564. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86565. });
  86566. this._lineShader.disableDepthWrite = true;
  86567. this._lineShader.backFaceCulling = false;
  86568. };
  86569. EdgesRenderer.prototype._rebuild = function () {
  86570. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86571. if (buffer) {
  86572. buffer._rebuild();
  86573. }
  86574. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86575. if (buffer) {
  86576. buffer._rebuild();
  86577. }
  86578. var scene = this._source.getScene();
  86579. var engine = scene.getEngine();
  86580. this._ib = engine.createIndexBuffer(this._linesIndices);
  86581. };
  86582. EdgesRenderer.prototype.dispose = function () {
  86583. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86584. if (buffer) {
  86585. buffer.dispose();
  86586. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86587. }
  86588. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86589. if (buffer) {
  86590. buffer.dispose();
  86591. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86592. }
  86593. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86594. this._lineShader.dispose();
  86595. };
  86596. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86597. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86598. return 0;
  86599. }
  86600. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86601. return 1;
  86602. }
  86603. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86604. return 2;
  86605. }
  86606. return -1;
  86607. };
  86608. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86609. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86610. return 0;
  86611. }
  86612. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86613. return 1;
  86614. }
  86615. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86616. return 2;
  86617. }
  86618. return -1;
  86619. };
  86620. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86621. var needToCreateLine;
  86622. if (edge === undefined) {
  86623. needToCreateLine = true;
  86624. }
  86625. else {
  86626. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86627. needToCreateLine = dotProduct < this._epsilon;
  86628. }
  86629. if (needToCreateLine) {
  86630. var offset = this._linesPositions.length / 3;
  86631. var normal = p0.subtract(p1);
  86632. normal.normalize();
  86633. // Positions
  86634. this._linesPositions.push(p0.x);
  86635. this._linesPositions.push(p0.y);
  86636. this._linesPositions.push(p0.z);
  86637. this._linesPositions.push(p0.x);
  86638. this._linesPositions.push(p0.y);
  86639. this._linesPositions.push(p0.z);
  86640. this._linesPositions.push(p1.x);
  86641. this._linesPositions.push(p1.y);
  86642. this._linesPositions.push(p1.z);
  86643. this._linesPositions.push(p1.x);
  86644. this._linesPositions.push(p1.y);
  86645. this._linesPositions.push(p1.z);
  86646. // Normals
  86647. this._linesNormals.push(p1.x);
  86648. this._linesNormals.push(p1.y);
  86649. this._linesNormals.push(p1.z);
  86650. this._linesNormals.push(-1);
  86651. this._linesNormals.push(p1.x);
  86652. this._linesNormals.push(p1.y);
  86653. this._linesNormals.push(p1.z);
  86654. this._linesNormals.push(1);
  86655. this._linesNormals.push(p0.x);
  86656. this._linesNormals.push(p0.y);
  86657. this._linesNormals.push(p0.z);
  86658. this._linesNormals.push(-1);
  86659. this._linesNormals.push(p0.x);
  86660. this._linesNormals.push(p0.y);
  86661. this._linesNormals.push(p0.z);
  86662. this._linesNormals.push(1);
  86663. // Indices
  86664. this._linesIndices.push(offset);
  86665. this._linesIndices.push(offset + 1);
  86666. this._linesIndices.push(offset + 2);
  86667. this._linesIndices.push(offset);
  86668. this._linesIndices.push(offset + 2);
  86669. this._linesIndices.push(offset + 3);
  86670. }
  86671. };
  86672. EdgesRenderer.prototype._generateEdgesLines = function () {
  86673. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86674. var indices = this._source.getIndices();
  86675. if (!indices || !positions) {
  86676. return;
  86677. }
  86678. // First let's find adjacencies
  86679. var adjacencies = new Array();
  86680. var faceNormals = new Array();
  86681. var index;
  86682. var faceAdjacencies;
  86683. // Prepare faces
  86684. for (index = 0; index < indices.length; index += 3) {
  86685. faceAdjacencies = new FaceAdjacencies();
  86686. var p0Index = indices[index];
  86687. var p1Index = indices[index + 1];
  86688. var p2Index = indices[index + 2];
  86689. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86690. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86691. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86692. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86693. faceNormal.normalize();
  86694. faceNormals.push(faceNormal);
  86695. adjacencies.push(faceAdjacencies);
  86696. }
  86697. // Scan
  86698. for (index = 0; index < adjacencies.length; index++) {
  86699. faceAdjacencies = adjacencies[index];
  86700. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86701. var otherFaceAdjacencies = adjacencies[otherIndex];
  86702. if (faceAdjacencies.edgesConnectedCount === 3) {
  86703. break;
  86704. }
  86705. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86706. continue;
  86707. }
  86708. var otherP0 = indices[otherIndex * 3];
  86709. var otherP1 = indices[otherIndex * 3 + 1];
  86710. var otherP2 = indices[otherIndex * 3 + 2];
  86711. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86712. var otherEdgeIndex = 0;
  86713. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86714. continue;
  86715. }
  86716. switch (edgeIndex) {
  86717. case 0:
  86718. if (this._checkVerticesInsteadOfIndices) {
  86719. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86720. }
  86721. else {
  86722. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86723. }
  86724. break;
  86725. case 1:
  86726. if (this._checkVerticesInsteadOfIndices) {
  86727. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86728. }
  86729. else {
  86730. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86731. }
  86732. break;
  86733. case 2:
  86734. if (this._checkVerticesInsteadOfIndices) {
  86735. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86736. }
  86737. else {
  86738. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86739. }
  86740. break;
  86741. }
  86742. if (otherEdgeIndex === -1) {
  86743. continue;
  86744. }
  86745. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86746. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86747. faceAdjacencies.edgesConnectedCount++;
  86748. otherFaceAdjacencies.edgesConnectedCount++;
  86749. if (faceAdjacencies.edgesConnectedCount === 3) {
  86750. break;
  86751. }
  86752. }
  86753. }
  86754. }
  86755. // Create lines
  86756. for (index = 0; index < adjacencies.length; index++) {
  86757. // 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
  86758. var current = adjacencies[index];
  86759. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86760. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86761. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86762. }
  86763. // Merge into a single mesh
  86764. var engine = this._source.getScene().getEngine();
  86765. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86766. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86767. this._ib = engine.createIndexBuffer(this._linesIndices);
  86768. this._indicesCount = this._linesIndices.length;
  86769. };
  86770. EdgesRenderer.prototype.render = function () {
  86771. var scene = this._source.getScene();
  86772. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86773. return;
  86774. }
  86775. var engine = scene.getEngine();
  86776. this._lineShader._preBind();
  86777. // VBOs
  86778. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86779. scene.resetCachedMaterial();
  86780. this._lineShader.setColor4("color", this._source.edgesColor);
  86781. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86782. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86783. }
  86784. else {
  86785. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86786. }
  86787. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86788. this._lineShader.bind(this._source.getWorldMatrix());
  86789. // Draw order
  86790. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86791. this._lineShader.unbind();
  86792. engine.setDepthWrite(true);
  86793. };
  86794. return EdgesRenderer;
  86795. }());
  86796. BABYLON.EdgesRenderer = EdgesRenderer;
  86797. })(BABYLON || (BABYLON = {}));
  86798. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86799. "use strict";
  86800. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86801. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86802. s = arguments[i];
  86803. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86804. t[p] = s[p];
  86805. }
  86806. return t;
  86807. };
  86808. var BABYLON;
  86809. (function (BABYLON) {
  86810. /**
  86811. * The effect layer Helps adding post process effect blended with the main pass.
  86812. *
  86813. * This can be for instance use to generate glow or higlight effects on the scene.
  86814. *
  86815. * The effect layer class can not be used directly and is intented to inherited from to be
  86816. * customized per effects.
  86817. */
  86818. var EffectLayer = /** @class */ (function () {
  86819. /**
  86820. * Instantiates a new effect Layer and references it in the scene.
  86821. * @param name The name of the layer
  86822. * @param scene The scene to use the layer in
  86823. */
  86824. function EffectLayer(
  86825. /** The Friendly of the effect in the scene */
  86826. name, scene) {
  86827. this.name = name;
  86828. this._vertexBuffers = {};
  86829. this._maxSize = 0;
  86830. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86831. this._shouldRender = true;
  86832. this._postProcesses = [];
  86833. this._textures = [];
  86834. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86835. /**
  86836. * The clear color of the texture used to generate the glow map.
  86837. */
  86838. this.neutralColor = new BABYLON.Color4();
  86839. /**
  86840. * Specifies wether the highlight layer is enabled or not.
  86841. */
  86842. this.isEnabled = true;
  86843. /**
  86844. * An event triggered when the effect layer has been disposed.
  86845. */
  86846. this.onDisposeObservable = new BABYLON.Observable();
  86847. /**
  86848. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86849. */
  86850. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86851. /**
  86852. * An event triggered when the generated texture is being merged in the scene.
  86853. */
  86854. this.onBeforeComposeObservable = new BABYLON.Observable();
  86855. /**
  86856. * An event triggered when the generated texture has been merged in the scene.
  86857. */
  86858. this.onAfterComposeObservable = new BABYLON.Observable();
  86859. /**
  86860. * An event triggered when the efffect layer changes its size.
  86861. */
  86862. this.onSizeChangedObservable = new BABYLON.Observable();
  86863. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86864. this._engine = scene.getEngine();
  86865. this._maxSize = this._engine.getCaps().maxTextureSize;
  86866. this._scene.effectLayers.push(this);
  86867. // Generate Buffers
  86868. this._generateIndexBuffer();
  86869. this._genrateVertexBuffer();
  86870. }
  86871. Object.defineProperty(EffectLayer.prototype, "camera", {
  86872. /**
  86873. * Gets the camera attached to the layer.
  86874. */
  86875. get: function () {
  86876. return this._effectLayerOptions.camera;
  86877. },
  86878. enumerable: true,
  86879. configurable: true
  86880. });
  86881. /**
  86882. * Initializes the effect layer with the required options.
  86883. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86884. */
  86885. EffectLayer.prototype._init = function (options) {
  86886. // Adapt options
  86887. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86888. this._setMainTextureSize();
  86889. this._createMainTexture();
  86890. this._createTextureAndPostProcesses();
  86891. this._mergeEffect = this._createMergeEffect();
  86892. };
  86893. /**
  86894. * Generates the index buffer of the full screen quad blending to the main canvas.
  86895. */
  86896. EffectLayer.prototype._generateIndexBuffer = function () {
  86897. // Indices
  86898. var indices = [];
  86899. indices.push(0);
  86900. indices.push(1);
  86901. indices.push(2);
  86902. indices.push(0);
  86903. indices.push(2);
  86904. indices.push(3);
  86905. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86906. };
  86907. /**
  86908. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86909. */
  86910. EffectLayer.prototype._genrateVertexBuffer = function () {
  86911. // VBO
  86912. var vertices = [];
  86913. vertices.push(1, 1);
  86914. vertices.push(-1, 1);
  86915. vertices.push(-1, -1);
  86916. vertices.push(1, -1);
  86917. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86918. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86919. };
  86920. /**
  86921. * Sets the main texture desired size which is the closest power of two
  86922. * of the engine canvas size.
  86923. */
  86924. EffectLayer.prototype._setMainTextureSize = function () {
  86925. if (this._effectLayerOptions.mainTextureFixedSize) {
  86926. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86927. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86928. }
  86929. else {
  86930. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86931. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86932. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86933. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86934. }
  86935. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86936. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86937. };
  86938. /**
  86939. * Creates the main texture for the effect layer.
  86940. */
  86941. EffectLayer.prototype._createMainTexture = function () {
  86942. var _this = this;
  86943. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86944. width: this._mainTextureDesiredSize.width,
  86945. height: this._mainTextureDesiredSize.height
  86946. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86947. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86948. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86949. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86950. this._mainTexture.anisotropicFilteringLevel = 1;
  86951. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86952. this._mainTexture.renderParticles = false;
  86953. this._mainTexture.renderList = null;
  86954. this._mainTexture.ignoreCameraViewport = true;
  86955. // Custom render function
  86956. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86957. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86958. var index;
  86959. var engine = _this._scene.getEngine();
  86960. if (depthOnlySubMeshes.length) {
  86961. engine.setColorWrite(false);
  86962. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86963. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86964. }
  86965. engine.setColorWrite(true);
  86966. }
  86967. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86968. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86969. }
  86970. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86971. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86972. }
  86973. for (index = 0; index < transparentSubMeshes.length; index++) {
  86974. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86975. }
  86976. };
  86977. this._mainTexture.onClearObservable.add(function (engine) {
  86978. engine.clear(_this.neutralColor, true, true, true);
  86979. });
  86980. };
  86981. /**
  86982. * Checks for the readiness of the element composing the layer.
  86983. * @param subMesh the mesh to check for
  86984. * @param useInstances specify wether or not to use instances to render the mesh
  86985. * @param emissiveTexture the associated emissive texture used to generate the glow
  86986. * @return true if ready otherwise, false
  86987. */
  86988. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86989. var material = subMesh.getMaterial();
  86990. if (!material) {
  86991. return false;
  86992. }
  86993. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86994. return false;
  86995. }
  86996. var defines = [];
  86997. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86998. var mesh = subMesh.getMesh();
  86999. var uv1 = false;
  87000. var uv2 = false;
  87001. // Alpha test
  87002. if (material && material.needAlphaTesting()) {
  87003. var alphaTexture = material.getAlphaTestTexture();
  87004. if (alphaTexture) {
  87005. defines.push("#define ALPHATEST");
  87006. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  87007. alphaTexture.coordinatesIndex === 1) {
  87008. defines.push("#define DIFFUSEUV2");
  87009. uv2 = true;
  87010. }
  87011. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87012. defines.push("#define DIFFUSEUV1");
  87013. uv1 = true;
  87014. }
  87015. }
  87016. }
  87017. // Emissive
  87018. if (emissiveTexture) {
  87019. defines.push("#define EMISSIVE");
  87020. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  87021. emissiveTexture.coordinatesIndex === 1) {
  87022. defines.push("#define EMISSIVEUV2");
  87023. uv2 = true;
  87024. }
  87025. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  87026. defines.push("#define EMISSIVEUV1");
  87027. uv1 = true;
  87028. }
  87029. }
  87030. if (uv1) {
  87031. attribs.push(BABYLON.VertexBuffer.UVKind);
  87032. defines.push("#define UV1");
  87033. }
  87034. if (uv2) {
  87035. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87036. defines.push("#define UV2");
  87037. }
  87038. // Bones
  87039. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  87040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  87041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  87042. if (mesh.numBoneInfluencers > 4) {
  87043. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  87044. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  87045. }
  87046. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  87047. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  87048. }
  87049. else {
  87050. defines.push("#define NUM_BONE_INFLUENCERS 0");
  87051. }
  87052. // Morph targets
  87053. var manager = mesh.morphTargetManager;
  87054. var morphInfluencers = 0;
  87055. if (manager) {
  87056. if (manager.numInfluencers > 0) {
  87057. defines.push("#define MORPHTARGETS");
  87058. morphInfluencers = manager.numInfluencers;
  87059. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  87060. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  87061. }
  87062. }
  87063. // Instances
  87064. if (useInstances) {
  87065. defines.push("#define INSTANCES");
  87066. attribs.push("world0");
  87067. attribs.push("world1");
  87068. attribs.push("world2");
  87069. attribs.push("world3");
  87070. }
  87071. // Get correct effect
  87072. var join = defines.join("\n");
  87073. if (this._cachedDefines !== join) {
  87074. this._cachedDefines = join;
  87075. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  87076. }
  87077. return this._effectLayerMapGenerationEffect.isReady();
  87078. };
  87079. /**
  87080. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  87081. */
  87082. EffectLayer.prototype.render = function () {
  87083. var currentEffect = this._mergeEffect;
  87084. // Check
  87085. if (!currentEffect.isReady())
  87086. return;
  87087. for (var i = 0; i < this._postProcesses.length; i++) {
  87088. if (!this._postProcesses[i].isReady()) {
  87089. return;
  87090. }
  87091. }
  87092. var engine = this._scene.getEngine();
  87093. this.onBeforeComposeObservable.notifyObservers(this);
  87094. // Render
  87095. engine.enableEffect(currentEffect);
  87096. engine.setState(false);
  87097. // VBOs
  87098. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  87099. // Cache
  87100. var previousAlphaMode = engine.getAlphaMode();
  87101. // Go Blend.
  87102. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  87103. // Blends the map on the main canvas.
  87104. this._internalRender(currentEffect);
  87105. // Restore Alpha
  87106. engine.setAlphaMode(previousAlphaMode);
  87107. this.onAfterComposeObservable.notifyObservers(this);
  87108. // Handle size changes.
  87109. var size = this._mainTexture.getSize();
  87110. this._setMainTextureSize();
  87111. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  87112. // Recreate RTT and post processes on size change.
  87113. this.onSizeChangedObservable.notifyObservers(this);
  87114. this._disposeTextureAndPostProcesses();
  87115. this._createMainTexture();
  87116. this._createTextureAndPostProcesses();
  87117. }
  87118. };
  87119. /**
  87120. * Determine if a given mesh will be used in the current effect.
  87121. * @param mesh mesh to test
  87122. * @returns true if the mesh will be used
  87123. */
  87124. EffectLayer.prototype.hasMesh = function (mesh) {
  87125. return true;
  87126. };
  87127. /**
  87128. * Returns true if the layer contains information to display, otherwise false.
  87129. * @returns true if the glow layer should be rendered
  87130. */
  87131. EffectLayer.prototype.shouldRender = function () {
  87132. return this.isEnabled && this._shouldRender;
  87133. };
  87134. /**
  87135. * Returns true if the mesh should render, otherwise false.
  87136. * @param mesh The mesh to render
  87137. * @returns true if it should render otherwise false
  87138. */
  87139. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  87140. return true;
  87141. };
  87142. /**
  87143. * Returns true if the mesh should render, otherwise false.
  87144. * @param mesh The mesh to render
  87145. * @returns true if it should render otherwise false
  87146. */
  87147. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  87148. return true;
  87149. };
  87150. /**
  87151. * Renders the submesh passed in parameter to the generation map.
  87152. */
  87153. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  87154. var _this = this;
  87155. if (!this.shouldRender()) {
  87156. return;
  87157. }
  87158. var material = subMesh.getMaterial();
  87159. var mesh = subMesh.getRenderingMesh();
  87160. var scene = this._scene;
  87161. var engine = scene.getEngine();
  87162. if (!material) {
  87163. return;
  87164. }
  87165. // Do not block in blend mode.
  87166. if (material.needAlphaBlendingForMesh(mesh)) {
  87167. return;
  87168. }
  87169. // Culling
  87170. engine.setState(material.backFaceCulling);
  87171. // Managing instances
  87172. var batch = mesh._getInstancesRenderList(subMesh._id);
  87173. if (batch.mustReturn) {
  87174. return;
  87175. }
  87176. // Early Exit per mesh
  87177. if (!this._shouldRenderMesh(mesh)) {
  87178. return;
  87179. }
  87180. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  87181. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  87182. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  87183. engine.enableEffect(this._effectLayerMapGenerationEffect);
  87184. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  87185. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  87186. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  87187. // Alpha test
  87188. if (material && material.needAlphaTesting()) {
  87189. var alphaTexture = material.getAlphaTestTexture();
  87190. if (alphaTexture) {
  87191. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  87192. var textureMatrix = alphaTexture.getTextureMatrix();
  87193. if (textureMatrix) {
  87194. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  87195. }
  87196. }
  87197. }
  87198. // Glow emissive only
  87199. if (this._emissiveTextureAndColor.texture) {
  87200. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  87201. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  87202. }
  87203. // Bones
  87204. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  87205. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  87206. }
  87207. // Morph targets
  87208. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  87209. // Draw
  87210. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  87211. }
  87212. else {
  87213. // Need to reset refresh rate of the shadowMap
  87214. this._mainTexture.resetRefreshCounter();
  87215. }
  87216. };
  87217. /**
  87218. * Rebuild the required buffers.
  87219. * @ignore Internal use only.
  87220. */
  87221. EffectLayer.prototype._rebuild = function () {
  87222. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87223. if (vb) {
  87224. vb._rebuild();
  87225. }
  87226. this._generateIndexBuffer();
  87227. };
  87228. /**
  87229. * Dispose only the render target textures and post process.
  87230. */
  87231. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  87232. this._mainTexture.dispose();
  87233. for (var i = 0; i < this._postProcesses.length; i++) {
  87234. if (this._postProcesses[i]) {
  87235. this._postProcesses[i].dispose();
  87236. }
  87237. }
  87238. this._postProcesses = [];
  87239. for (var i = 0; i < this._textures.length; i++) {
  87240. if (this._textures[i]) {
  87241. this._textures[i].dispose();
  87242. }
  87243. }
  87244. this._textures = [];
  87245. };
  87246. /**
  87247. * Dispose the highlight layer and free resources.
  87248. */
  87249. EffectLayer.prototype.dispose = function () {
  87250. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87251. if (vertexBuffer) {
  87252. vertexBuffer.dispose();
  87253. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87254. }
  87255. if (this._indexBuffer) {
  87256. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87257. this._indexBuffer = null;
  87258. }
  87259. // Clean textures and post processes
  87260. this._disposeTextureAndPostProcesses();
  87261. // Remove from scene
  87262. var index = this._scene.effectLayers.indexOf(this, 0);
  87263. if (index > -1) {
  87264. this._scene.effectLayers.splice(index, 1);
  87265. }
  87266. // Callback
  87267. this.onDisposeObservable.notifyObservers(this);
  87268. this.onDisposeObservable.clear();
  87269. this.onBeforeRenderMainTextureObservable.clear();
  87270. this.onBeforeComposeObservable.clear();
  87271. this.onAfterComposeObservable.clear();
  87272. this.onSizeChangedObservable.clear();
  87273. };
  87274. return EffectLayer;
  87275. }());
  87276. BABYLON.EffectLayer = EffectLayer;
  87277. })(BABYLON || (BABYLON = {}));
  87278. //# sourceMappingURL=babylon.effectLayer.js.map
  87279. "use strict";
  87280. var BABYLON;
  87281. (function (BABYLON) {
  87282. /**
  87283. * Special Glow Blur post process only blurring the alpha channel
  87284. * It enforces keeping the most luminous color in the color channel.
  87285. */
  87286. var GlowBlurPostProcess = /** @class */ (function (_super) {
  87287. __extends(GlowBlurPostProcess, _super);
  87288. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  87289. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87290. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  87291. _this.direction = direction;
  87292. _this.kernel = kernel;
  87293. _this.onApplyObservable.add(function (effect) {
  87294. effect.setFloat2("screenSize", _this.width, _this.height);
  87295. effect.setVector2("direction", _this.direction);
  87296. effect.setFloat("blurWidth", _this.kernel);
  87297. });
  87298. return _this;
  87299. }
  87300. return GlowBlurPostProcess;
  87301. }(BABYLON.PostProcess));
  87302. /**
  87303. * The highlight layer Helps adding a glow effect around a mesh.
  87304. *
  87305. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87306. * glowy meshes to your scene.
  87307. *
  87308. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  87309. */
  87310. var HighlightLayer = /** @class */ (function (_super) {
  87311. __extends(HighlightLayer, _super);
  87312. /**
  87313. * Instantiates a new highlight Layer and references it to the scene..
  87314. * @param name The name of the layer
  87315. * @param scene The scene to use the layer in
  87316. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  87317. */
  87318. function HighlightLayer(name, scene, options) {
  87319. var _this = _super.call(this, name, scene) || this;
  87320. _this.name = name;
  87321. /**
  87322. * Specifies whether or not the inner glow is ACTIVE in the layer.
  87323. */
  87324. _this.innerGlow = true;
  87325. /**
  87326. * Specifies whether or not the outer glow is ACTIVE in the layer.
  87327. */
  87328. _this.outerGlow = true;
  87329. /**
  87330. * An event triggered when the highlight layer is being blurred.
  87331. */
  87332. _this.onBeforeBlurObservable = new BABYLON.Observable();
  87333. /**
  87334. * An event triggered when the highlight layer has been blurred.
  87335. */
  87336. _this.onAfterBlurObservable = new BABYLON.Observable();
  87337. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  87338. _this._meshes = {};
  87339. _this._excludedMeshes = {};
  87340. _this.neutralColor = HighlightLayer.NeutralColor;
  87341. // Warn on stencil
  87342. if (!_this._engine.isStencilEnable) {
  87343. 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 }");
  87344. }
  87345. // Adapt options
  87346. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87347. // Initialize the layer
  87348. _this._init({
  87349. alphaBlendingMode: _this._options.alphaBlendingMode,
  87350. camera: _this._options.camera,
  87351. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87352. mainTextureRatio: _this._options.mainTextureRatio
  87353. });
  87354. // Do not render as long as no meshes have been added
  87355. _this._shouldRender = false;
  87356. return _this;
  87357. }
  87358. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87359. /**
  87360. * Gets the horizontal size of the blur.
  87361. */
  87362. get: function () {
  87363. return this._horizontalBlurPostprocess.kernel;
  87364. },
  87365. /**
  87366. * Specifies the horizontal size of the blur.
  87367. */
  87368. set: function (value) {
  87369. this._horizontalBlurPostprocess.kernel = value;
  87370. },
  87371. enumerable: true,
  87372. configurable: true
  87373. });
  87374. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87375. /**
  87376. * Gets the vertical size of the blur.
  87377. */
  87378. get: function () {
  87379. return this._verticalBlurPostprocess.kernel;
  87380. },
  87381. /**
  87382. * Specifies the vertical size of the blur.
  87383. */
  87384. set: function (value) {
  87385. this._verticalBlurPostprocess.kernel = value;
  87386. },
  87387. enumerable: true,
  87388. configurable: true
  87389. });
  87390. /**
  87391. * Get the effect name of the layer.
  87392. * @return The effect name
  87393. */
  87394. HighlightLayer.prototype.getEffectName = function () {
  87395. return HighlightLayer.EffectName;
  87396. };
  87397. /**
  87398. * Create the merge effect. This is the shader use to blit the information back
  87399. * to the main canvas at the end of the scene rendering.
  87400. */
  87401. HighlightLayer.prototype._createMergeEffect = function () {
  87402. // Effect
  87403. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87404. };
  87405. /**
  87406. * Creates the render target textures and post processes used in the highlight layer.
  87407. */
  87408. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87409. var _this = this;
  87410. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87411. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87412. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87413. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87414. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87415. width: blurTextureWidth,
  87416. height: blurTextureHeight
  87417. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87418. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87419. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87420. this._blurTexture.anisotropicFilteringLevel = 16;
  87421. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87422. this._blurTexture.renderParticles = false;
  87423. this._blurTexture.ignoreCameraViewport = true;
  87424. this._textures = [this._blurTexture];
  87425. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87426. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87427. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87428. effect.setTexture("textureSampler", _this._mainTexture);
  87429. });
  87430. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87431. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87432. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87433. });
  87434. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87435. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87436. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87437. });
  87438. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87439. }
  87440. else {
  87441. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87442. width: blurTextureWidth,
  87443. height: blurTextureHeight
  87444. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87445. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87446. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87447. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87448. effect.setTexture("textureSampler", _this._mainTexture);
  87449. });
  87450. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87451. width: blurTextureWidth,
  87452. height: blurTextureHeight
  87453. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87454. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87455. }
  87456. this._mainTexture.onAfterUnbindObservable.add(function () {
  87457. _this.onBeforeBlurObservable.notifyObservers(_this);
  87458. var internalTexture = _this._blurTexture.getInternalTexture();
  87459. if (internalTexture) {
  87460. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87461. }
  87462. _this.onAfterBlurObservable.notifyObservers(_this);
  87463. });
  87464. // Prevent autoClear.
  87465. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87466. };
  87467. /**
  87468. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87469. */
  87470. HighlightLayer.prototype.needStencil = function () {
  87471. return true;
  87472. };
  87473. /**
  87474. * Checks for the readiness of the element composing the layer.
  87475. * @param subMesh the mesh to check for
  87476. * @param useInstances specify wether or not to use instances to render the mesh
  87477. * @param emissiveTexture the associated emissive texture used to generate the glow
  87478. * @return true if ready otherwise, false
  87479. */
  87480. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87481. var material = subMesh.getMaterial();
  87482. var mesh = subMesh.getRenderingMesh();
  87483. if (!material || !mesh || !this._meshes) {
  87484. return false;
  87485. }
  87486. var emissiveTexture = null;
  87487. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87488. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87489. emissiveTexture = material.emissiveTexture;
  87490. }
  87491. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87492. };
  87493. /**
  87494. * Implementation specific of rendering the generating effect on the main canvas.
  87495. * @param effect The effect used to render through
  87496. */
  87497. HighlightLayer.prototype._internalRender = function (effect) {
  87498. // Texture
  87499. effect.setTexture("textureSampler", this._blurTexture);
  87500. // Cache
  87501. var engine = this._engine;
  87502. var previousStencilBuffer = engine.getStencilBuffer();
  87503. var previousStencilFunction = engine.getStencilFunction();
  87504. var previousStencilMask = engine.getStencilMask();
  87505. var previousStencilOperationPass = engine.getStencilOperationPass();
  87506. var previousStencilOperationFail = engine.getStencilOperationFail();
  87507. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87508. var previousStencilReference = engine.getStencilFunctionReference();
  87509. // Stencil operations
  87510. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87511. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87512. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87513. // Draw order
  87514. engine.setStencilMask(0x00);
  87515. engine.setStencilBuffer(true);
  87516. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87517. // 2 passes inner outer
  87518. if (this.outerGlow) {
  87519. effect.setFloat("offset", 0);
  87520. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87521. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87522. }
  87523. if (this.innerGlow) {
  87524. effect.setFloat("offset", 1);
  87525. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87526. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87527. }
  87528. // Restore Cache
  87529. engine.setStencilFunction(previousStencilFunction);
  87530. engine.setStencilMask(previousStencilMask);
  87531. engine.setStencilBuffer(previousStencilBuffer);
  87532. engine.setStencilOperationPass(previousStencilOperationPass);
  87533. engine.setStencilOperationFail(previousStencilOperationFail);
  87534. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87535. engine.setStencilFunctionReference(previousStencilReference);
  87536. };
  87537. /**
  87538. * Returns true if the layer contains information to display, otherwise false.
  87539. */
  87540. HighlightLayer.prototype.shouldRender = function () {
  87541. if (_super.prototype.shouldRender.call(this)) {
  87542. return this._meshes ? true : false;
  87543. }
  87544. return false;
  87545. };
  87546. /**
  87547. * Returns true if the mesh should render, otherwise false.
  87548. * @param mesh The mesh to render
  87549. * @returns true if it should render otherwise false
  87550. */
  87551. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87552. // Excluded Mesh
  87553. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87554. return false;
  87555. }
  87556. ;
  87557. return true;
  87558. };
  87559. /**
  87560. * Sets the required values for both the emissive texture and and the main color.
  87561. */
  87562. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87563. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87564. if (highlightLayerMesh) {
  87565. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87566. }
  87567. else {
  87568. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87569. }
  87570. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87571. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87572. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87573. }
  87574. else {
  87575. this._emissiveTextureAndColor.texture = null;
  87576. }
  87577. };
  87578. /**
  87579. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87580. * @param mesh The mesh to exclude from the highlight layer
  87581. */
  87582. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87583. if (!this._excludedMeshes) {
  87584. return;
  87585. }
  87586. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87587. if (!meshExcluded) {
  87588. this._excludedMeshes[mesh.uniqueId] = {
  87589. mesh: mesh,
  87590. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87591. mesh.getEngine().setStencilBuffer(false);
  87592. }),
  87593. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87594. mesh.getEngine().setStencilBuffer(true);
  87595. }),
  87596. };
  87597. }
  87598. };
  87599. /**
  87600. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87601. * @param mesh The mesh to highlight
  87602. */
  87603. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87604. if (!this._excludedMeshes) {
  87605. return;
  87606. }
  87607. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87608. if (meshExcluded) {
  87609. if (meshExcluded.beforeRender) {
  87610. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87611. }
  87612. if (meshExcluded.afterRender) {
  87613. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87614. }
  87615. }
  87616. this._excludedMeshes[mesh.uniqueId] = null;
  87617. };
  87618. /**
  87619. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87620. * @param mesh mesh to test
  87621. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87622. */
  87623. HighlightLayer.prototype.hasMesh = function (mesh) {
  87624. if (!this._meshes) {
  87625. return false;
  87626. }
  87627. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87628. };
  87629. /**
  87630. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87631. * @param mesh The mesh to highlight
  87632. * @param color The color of the highlight
  87633. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87634. */
  87635. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87636. var _this = this;
  87637. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87638. if (!this._meshes) {
  87639. return;
  87640. }
  87641. var meshHighlight = this._meshes[mesh.uniqueId];
  87642. if (meshHighlight) {
  87643. meshHighlight.color = color;
  87644. }
  87645. else {
  87646. this._meshes[mesh.uniqueId] = {
  87647. mesh: mesh,
  87648. color: color,
  87649. // Lambda required for capture due to Observable this context
  87650. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87651. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87652. _this._defaultStencilReference(mesh);
  87653. }
  87654. else {
  87655. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87656. }
  87657. }),
  87658. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87659. glowEmissiveOnly: glowEmissiveOnly
  87660. };
  87661. }
  87662. this._shouldRender = true;
  87663. };
  87664. /**
  87665. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87666. * @param mesh The mesh to highlight
  87667. */
  87668. HighlightLayer.prototype.removeMesh = function (mesh) {
  87669. if (!this._meshes) {
  87670. return;
  87671. }
  87672. var meshHighlight = this._meshes[mesh.uniqueId];
  87673. if (meshHighlight) {
  87674. if (meshHighlight.observerHighlight) {
  87675. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87676. }
  87677. if (meshHighlight.observerDefault) {
  87678. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87679. }
  87680. delete this._meshes[mesh.uniqueId];
  87681. }
  87682. this._shouldRender = false;
  87683. for (var meshHighlightToCheck in this._meshes) {
  87684. if (this._meshes[meshHighlightToCheck]) {
  87685. this._shouldRender = true;
  87686. break;
  87687. }
  87688. }
  87689. };
  87690. /**
  87691. * Force the stencil to the normal expected value for none glowing parts
  87692. */
  87693. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87694. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87695. };
  87696. /**
  87697. * Free any resources and references associated to a mesh.
  87698. * Internal use
  87699. * @param mesh The mesh to free.
  87700. */
  87701. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87702. this.removeMesh(mesh);
  87703. this.removeExcludedMesh(mesh);
  87704. };
  87705. /**
  87706. * Dispose the highlight layer and free resources.
  87707. */
  87708. HighlightLayer.prototype.dispose = function () {
  87709. if (this._meshes) {
  87710. // Clean mesh references
  87711. for (var id in this._meshes) {
  87712. var meshHighlight = this._meshes[id];
  87713. if (meshHighlight && meshHighlight.mesh) {
  87714. if (meshHighlight.observerHighlight) {
  87715. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87716. }
  87717. if (meshHighlight.observerDefault) {
  87718. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87719. }
  87720. }
  87721. }
  87722. this._meshes = null;
  87723. }
  87724. if (this._excludedMeshes) {
  87725. for (var id in this._excludedMeshes) {
  87726. var meshHighlight = this._excludedMeshes[id];
  87727. if (meshHighlight) {
  87728. if (meshHighlight.beforeRender) {
  87729. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87730. }
  87731. if (meshHighlight.afterRender) {
  87732. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87733. }
  87734. }
  87735. }
  87736. this._excludedMeshes = null;
  87737. }
  87738. _super.prototype.dispose.call(this);
  87739. };
  87740. /**
  87741. * Effect Name of the highlight layer.
  87742. */
  87743. HighlightLayer.EffectName = "HighlightLayer";
  87744. /**
  87745. * The neutral color used during the preparation of the glow effect.
  87746. * This is black by default as the blend operation is a blend operation.
  87747. */
  87748. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87749. /**
  87750. * Stencil value used for glowing meshes.
  87751. */
  87752. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87753. /**
  87754. * Stencil value used for the other meshes in the scene.
  87755. */
  87756. HighlightLayer.NormalMeshStencilReference = 0x01;
  87757. return HighlightLayer;
  87758. }(BABYLON.EffectLayer));
  87759. BABYLON.HighlightLayer = HighlightLayer;
  87760. })(BABYLON || (BABYLON = {}));
  87761. //# sourceMappingURL=babylon.highlightLayer.js.map
  87762. "use strict";
  87763. var BABYLON;
  87764. (function (BABYLON) {
  87765. /**
  87766. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87767. *
  87768. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87769. * glowy meshes to your scene.
  87770. *
  87771. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87772. */
  87773. var GlowLayer = /** @class */ (function (_super) {
  87774. __extends(GlowLayer, _super);
  87775. /**
  87776. * Instantiates a new glow Layer and references it to the scene.
  87777. * @param name The name of the layer
  87778. * @param scene The scene to use the layer in
  87779. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87780. */
  87781. function GlowLayer(name, scene, options) {
  87782. var _this = _super.call(this, name, scene) || this;
  87783. _this.name = name;
  87784. _this._intensity = 1.0;
  87785. _this._includedOnlyMeshes = [];
  87786. _this._excludedMeshes = [];
  87787. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87788. // Adapt options
  87789. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87790. // Initialize the layer
  87791. _this._init({
  87792. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87793. camera: _this._options.camera,
  87794. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87795. mainTextureRatio: _this._options.mainTextureRatio
  87796. });
  87797. return _this;
  87798. }
  87799. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87800. /**
  87801. * Gets the kernel size of the blur.
  87802. */
  87803. get: function () {
  87804. return this._horizontalBlurPostprocess1.kernel;
  87805. },
  87806. /**
  87807. * Sets the kernel size of the blur.
  87808. */
  87809. set: function (value) {
  87810. this._horizontalBlurPostprocess1.kernel = value;
  87811. this._verticalBlurPostprocess1.kernel = value;
  87812. this._horizontalBlurPostprocess2.kernel = value;
  87813. this._verticalBlurPostprocess2.kernel = value;
  87814. },
  87815. enumerable: true,
  87816. configurable: true
  87817. });
  87818. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87819. /**
  87820. * Gets the glow intensity.
  87821. */
  87822. get: function () {
  87823. return this._intensity;
  87824. },
  87825. /**
  87826. * Sets the glow intensity.
  87827. */
  87828. set: function (value) {
  87829. this._intensity = value;
  87830. },
  87831. enumerable: true,
  87832. configurable: true
  87833. });
  87834. /**
  87835. * Get the effect name of the layer.
  87836. * @return The effect name
  87837. */
  87838. GlowLayer.prototype.getEffectName = function () {
  87839. return GlowLayer.EffectName;
  87840. };
  87841. /**
  87842. * Create the merge effect. This is the shader use to blit the information back
  87843. * to the main canvas at the end of the scene rendering.
  87844. */
  87845. GlowLayer.prototype._createMergeEffect = function () {
  87846. // Effect
  87847. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87848. };
  87849. /**
  87850. * Creates the render target textures and post processes used in the glow layer.
  87851. */
  87852. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87853. var _this = this;
  87854. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87855. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87856. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87857. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87858. var textureType = 0;
  87859. if (this._engine.getCaps().textureHalfFloatRender) {
  87860. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87861. }
  87862. else {
  87863. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87864. }
  87865. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87866. width: blurTextureWidth,
  87867. height: blurTextureHeight
  87868. }, this._scene, false, true, textureType);
  87869. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87870. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87871. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87872. this._blurTexture1.renderParticles = false;
  87873. this._blurTexture1.ignoreCameraViewport = true;
  87874. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87875. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87876. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87877. width: blurTextureWidth2,
  87878. height: blurTextureHeight2
  87879. }, this._scene, false, true, textureType);
  87880. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87881. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87882. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87883. this._blurTexture2.renderParticles = false;
  87884. this._blurTexture2.ignoreCameraViewport = true;
  87885. this._textures = [this._blurTexture1, this._blurTexture2];
  87886. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87887. width: blurTextureWidth,
  87888. height: blurTextureHeight
  87889. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87890. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87891. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87892. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87893. effect.setTexture("textureSampler", _this._mainTexture);
  87894. });
  87895. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87896. width: blurTextureWidth,
  87897. height: blurTextureHeight
  87898. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87899. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87900. width: blurTextureWidth2,
  87901. height: blurTextureHeight2
  87902. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87903. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87904. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87905. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87906. effect.setTexture("textureSampler", _this._blurTexture1);
  87907. });
  87908. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87909. width: blurTextureWidth2,
  87910. height: blurTextureHeight2
  87911. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  87912. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87913. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87914. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87915. this._mainTexture.samples = this._options.mainTextureSamples;
  87916. this._mainTexture.onAfterUnbindObservable.add(function () {
  87917. var internalTexture = _this._blurTexture1.getInternalTexture();
  87918. if (internalTexture) {
  87919. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87920. internalTexture = _this._blurTexture2.getInternalTexture();
  87921. if (internalTexture) {
  87922. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87923. }
  87924. }
  87925. });
  87926. // Prevent autoClear.
  87927. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87928. };
  87929. /**
  87930. * Checks for the readiness of the element composing the layer.
  87931. * @param subMesh the mesh to check for
  87932. * @param useInstances specify wether or not to use instances to render the mesh
  87933. * @param emissiveTexture the associated emissive texture used to generate the glow
  87934. * @return true if ready otherwise, false
  87935. */
  87936. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87937. var material = subMesh.getMaterial();
  87938. var mesh = subMesh.getRenderingMesh();
  87939. if (!material || !mesh) {
  87940. return false;
  87941. }
  87942. var emissiveTexture = material.emissiveTexture;
  87943. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87944. };
  87945. /**
  87946. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87947. */
  87948. GlowLayer.prototype.needStencil = function () {
  87949. return false;
  87950. };
  87951. /**
  87952. * Implementation specific of rendering the generating effect on the main canvas.
  87953. * @param effect The effect used to render through
  87954. */
  87955. GlowLayer.prototype._internalRender = function (effect) {
  87956. // Texture
  87957. effect.setTexture("textureSampler", this._blurTexture1);
  87958. effect.setTexture("textureSampler2", this._blurTexture2);
  87959. effect.setFloat("offset", this._intensity);
  87960. // Cache
  87961. var engine = this._engine;
  87962. var previousStencilBuffer = engine.getStencilBuffer();
  87963. // Draw order
  87964. engine.setStencilBuffer(false);
  87965. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87966. // Draw order
  87967. engine.setStencilBuffer(previousStencilBuffer);
  87968. };
  87969. /**
  87970. * Sets the required values for both the emissive texture and and the main color.
  87971. */
  87972. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87973. var textureLevel = 1.0;
  87974. if (this.customEmissiveTextureSelector) {
  87975. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87976. }
  87977. else {
  87978. if (material) {
  87979. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87980. if (this._emissiveTextureAndColor.texture) {
  87981. textureLevel = this._emissiveTextureAndColor.texture.level;
  87982. }
  87983. }
  87984. else {
  87985. this._emissiveTextureAndColor.texture = null;
  87986. }
  87987. }
  87988. if (this.customEmissiveColorSelector) {
  87989. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87990. }
  87991. else {
  87992. if (material.emissiveColor) {
  87993. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87994. }
  87995. else {
  87996. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87997. }
  87998. }
  87999. };
  88000. /**
  88001. * Returns true if the mesh should render, otherwise false.
  88002. * @param mesh The mesh to render
  88003. * @returns true if it should render otherwise false
  88004. */
  88005. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  88006. return this.hasMesh(mesh);
  88007. };
  88008. /**
  88009. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  88010. * @param mesh The mesh to exclude from the glow layer
  88011. */
  88012. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  88013. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  88014. this._excludedMeshes.push(mesh.uniqueId);
  88015. }
  88016. };
  88017. /**
  88018. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  88019. * @param mesh The mesh to remove
  88020. */
  88021. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  88022. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  88023. if (index !== -1) {
  88024. this._excludedMeshes.splice(index, 1);
  88025. }
  88026. };
  88027. /**
  88028. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  88029. * @param mesh The mesh to include in the glow layer
  88030. */
  88031. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  88032. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  88033. this._includedOnlyMeshes.push(mesh.uniqueId);
  88034. }
  88035. };
  88036. /**
  88037. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  88038. * @param mesh The mesh to remove
  88039. */
  88040. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  88041. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  88042. if (index !== -1) {
  88043. this._includedOnlyMeshes.splice(index, 1);
  88044. }
  88045. };
  88046. /**
  88047. * Determine if a given mesh will be used in the glow layer
  88048. * @param mesh The mesh to test
  88049. * @returns true if the mesh will be highlighted by the current glow layer
  88050. */
  88051. GlowLayer.prototype.hasMesh = function (mesh) {
  88052. // Included Mesh
  88053. if (this._includedOnlyMeshes.length) {
  88054. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  88055. }
  88056. ;
  88057. // Excluded Mesh
  88058. if (this._excludedMeshes.length) {
  88059. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  88060. }
  88061. ;
  88062. return true;
  88063. };
  88064. /**
  88065. * Free any resources and references associated to a mesh.
  88066. * Internal use
  88067. * @param mesh The mesh to free.
  88068. */
  88069. GlowLayer.prototype._disposeMesh = function (mesh) {
  88070. this.removeIncludedOnlyMesh(mesh);
  88071. this.removeExcludedMesh(mesh);
  88072. };
  88073. /**
  88074. * Effect Name of the layer.
  88075. */
  88076. GlowLayer.EffectName = "GlowLayer";
  88077. /**
  88078. * The default blur kernel size used for the glow.
  88079. */
  88080. GlowLayer.DefaultBlurKernelSize = 32;
  88081. /**
  88082. * The default texture size ratio used for the glow.
  88083. */
  88084. GlowLayer.DefaultTextureRatio = 0.5;
  88085. return GlowLayer;
  88086. }(BABYLON.EffectLayer));
  88087. BABYLON.GlowLayer = GlowLayer;
  88088. })(BABYLON || (BABYLON = {}));
  88089. //# sourceMappingURL=babylon.glowLayer.js.map
  88090. "use strict";
  88091. var BABYLON;
  88092. (function (BABYLON) {
  88093. /**
  88094. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  88095. */
  88096. var AssetTaskState;
  88097. (function (AssetTaskState) {
  88098. /**
  88099. * Initialization
  88100. */
  88101. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  88102. /**
  88103. * Running
  88104. */
  88105. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  88106. /**
  88107. * Done
  88108. */
  88109. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  88110. /**
  88111. * Error
  88112. */
  88113. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  88114. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  88115. /**
  88116. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  88117. */
  88118. var AbstractAssetTask = /** @class */ (function () {
  88119. /**
  88120. * Creates a new {BABYLON.AssetsManager}
  88121. * @param name defines the name of the task
  88122. */
  88123. function AbstractAssetTask(
  88124. /**
  88125. * Task name
  88126. */ name) {
  88127. this.name = name;
  88128. this._isCompleted = false;
  88129. this._taskState = AssetTaskState.INIT;
  88130. }
  88131. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  88132. /**
  88133. * Get if the task is completed
  88134. */
  88135. get: function () {
  88136. return this._isCompleted;
  88137. },
  88138. enumerable: true,
  88139. configurable: true
  88140. });
  88141. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  88142. /**
  88143. * Gets the current state of the task
  88144. */
  88145. get: function () {
  88146. return this._taskState;
  88147. },
  88148. enumerable: true,
  88149. configurable: true
  88150. });
  88151. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  88152. /**
  88153. * Gets the current error object (if task is in error)
  88154. */
  88155. get: function () {
  88156. return this._errorObject;
  88157. },
  88158. enumerable: true,
  88159. configurable: true
  88160. });
  88161. /**
  88162. * Internal only
  88163. * @ignore
  88164. */
  88165. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  88166. if (this._errorObject) {
  88167. return;
  88168. }
  88169. this._errorObject = {
  88170. message: message,
  88171. exception: exception
  88172. };
  88173. };
  88174. /**
  88175. * Execute the current task
  88176. * @param scene defines the scene where you want your assets to be loaded
  88177. * @param onSuccess is a callback called when the task is successfully executed
  88178. * @param onError is a callback called if an error occurs
  88179. */
  88180. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88181. var _this = this;
  88182. this._taskState = AssetTaskState.RUNNING;
  88183. this.runTask(scene, function () {
  88184. _this.onDoneCallback(onSuccess, onError);
  88185. }, function (msg, exception) {
  88186. _this.onErrorCallback(onError, msg, exception);
  88187. });
  88188. };
  88189. /**
  88190. * Execute the current task
  88191. * @param scene defines the scene where you want your assets to be loaded
  88192. * @param onSuccess is a callback called when the task is successfully executed
  88193. * @param onError is a callback called if an error occurs
  88194. */
  88195. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88196. throw new Error("runTask is not implemented");
  88197. };
  88198. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  88199. this._taskState = AssetTaskState.ERROR;
  88200. this._errorObject = {
  88201. message: message,
  88202. exception: exception
  88203. };
  88204. if (this.onError) {
  88205. this.onError(this, message, exception);
  88206. }
  88207. onError();
  88208. };
  88209. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  88210. try {
  88211. this._taskState = AssetTaskState.DONE;
  88212. this._isCompleted = true;
  88213. if (this.onSuccess) {
  88214. this.onSuccess(this);
  88215. }
  88216. onSuccess();
  88217. }
  88218. catch (e) {
  88219. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  88220. }
  88221. };
  88222. return AbstractAssetTask;
  88223. }());
  88224. BABYLON.AbstractAssetTask = AbstractAssetTask;
  88225. /**
  88226. * Class used to share progress information about assets loading
  88227. */
  88228. var AssetsProgressEvent = /** @class */ (function () {
  88229. /**
  88230. * Creates a {BABYLON.AssetsProgressEvent}
  88231. * @param remainingCount defines the number of remaining tasks to process
  88232. * @param totalCount defines the total number of tasks
  88233. * @param task defines the task that was just processed
  88234. */
  88235. function AssetsProgressEvent(remainingCount, totalCount, task) {
  88236. this.remainingCount = remainingCount;
  88237. this.totalCount = totalCount;
  88238. this.task = task;
  88239. }
  88240. return AssetsProgressEvent;
  88241. }());
  88242. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  88243. /**
  88244. * Define a task used by {BABYLON.AssetsManager} to load meshes
  88245. */
  88246. var MeshAssetTask = /** @class */ (function (_super) {
  88247. __extends(MeshAssetTask, _super);
  88248. /**
  88249. * Creates a new {BABYLON.MeshAssetTask}
  88250. * @param name defines the name of the task
  88251. * @param meshesNames defines the list of mesh's names you want to load
  88252. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  88253. * @param sceneFilename defines the filename of the scene to load from
  88254. */
  88255. function MeshAssetTask(
  88256. /**
  88257. * Defines the name of the task
  88258. */
  88259. name,
  88260. /**
  88261. * Defines the list of mesh's names you want to load
  88262. */
  88263. meshesNames,
  88264. /**
  88265. * Defines the root url to use as a base to load your meshes and associated resources
  88266. */
  88267. rootUrl,
  88268. /**
  88269. * Defines the filename of the scene to load from
  88270. */
  88271. sceneFilename) {
  88272. var _this = _super.call(this, name) || this;
  88273. _this.name = name;
  88274. _this.meshesNames = meshesNames;
  88275. _this.rootUrl = rootUrl;
  88276. _this.sceneFilename = sceneFilename;
  88277. return _this;
  88278. }
  88279. /**
  88280. * Execute the current task
  88281. * @param scene defines the scene where you want your assets to be loaded
  88282. * @param onSuccess is a callback called when the task is successfully executed
  88283. * @param onError is a callback called if an error occurs
  88284. */
  88285. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88286. var _this = this;
  88287. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  88288. _this.loadedMeshes = meshes;
  88289. _this.loadedParticleSystems = particleSystems;
  88290. _this.loadedSkeletons = skeletons;
  88291. onSuccess();
  88292. }, null, function (scene, message, exception) {
  88293. onError(message, exception);
  88294. });
  88295. };
  88296. return MeshAssetTask;
  88297. }(AbstractAssetTask));
  88298. BABYLON.MeshAssetTask = MeshAssetTask;
  88299. /**
  88300. * Define a task used by {BABYLON.AssetsManager} to load text content
  88301. */
  88302. var TextFileAssetTask = /** @class */ (function (_super) {
  88303. __extends(TextFileAssetTask, _super);
  88304. /**
  88305. * Creates a new TextFileAssetTask object
  88306. * @param name defines the name of the task
  88307. * @param url defines the location of the file to load
  88308. */
  88309. function TextFileAssetTask(
  88310. /**
  88311. * Defines the name of the task
  88312. */
  88313. name,
  88314. /**
  88315. * Defines the location of the file to load
  88316. */
  88317. url) {
  88318. var _this = _super.call(this, name) || this;
  88319. _this.name = name;
  88320. _this.url = url;
  88321. return _this;
  88322. }
  88323. /**
  88324. * Execute the current task
  88325. * @param scene defines the scene where you want your assets to be loaded
  88326. * @param onSuccess is a callback called when the task is successfully executed
  88327. * @param onError is a callback called if an error occurs
  88328. */
  88329. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88330. var _this = this;
  88331. scene._loadFile(this.url, function (data) {
  88332. _this.text = data;
  88333. onSuccess();
  88334. }, undefined, false, false, function (request, exception) {
  88335. if (request) {
  88336. onError(request.status + " " + request.statusText, exception);
  88337. }
  88338. });
  88339. };
  88340. return TextFileAssetTask;
  88341. }(AbstractAssetTask));
  88342. BABYLON.TextFileAssetTask = TextFileAssetTask;
  88343. /**
  88344. * Define a task used by {BABYLON.AssetsManager} to load binary data
  88345. */
  88346. var BinaryFileAssetTask = /** @class */ (function (_super) {
  88347. __extends(BinaryFileAssetTask, _super);
  88348. /**
  88349. * Creates a new BinaryFileAssetTask object
  88350. * @param name defines the name of the new task
  88351. * @param url defines the location of the file to load
  88352. */
  88353. function BinaryFileAssetTask(
  88354. /**
  88355. * Defines the name of the task
  88356. */
  88357. name,
  88358. /**
  88359. * Defines the location of the file to load
  88360. */
  88361. url) {
  88362. var _this = _super.call(this, name) || this;
  88363. _this.name = name;
  88364. _this.url = url;
  88365. return _this;
  88366. }
  88367. /**
  88368. * Execute the current task
  88369. * @param scene defines the scene where you want your assets to be loaded
  88370. * @param onSuccess is a callback called when the task is successfully executed
  88371. * @param onError is a callback called if an error occurs
  88372. */
  88373. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88374. var _this = this;
  88375. scene._loadFile(this.url, function (data) {
  88376. _this.data = data;
  88377. onSuccess();
  88378. }, undefined, true, true, function (request, exception) {
  88379. if (request) {
  88380. onError(request.status + " " + request.statusText, exception);
  88381. }
  88382. });
  88383. };
  88384. return BinaryFileAssetTask;
  88385. }(AbstractAssetTask));
  88386. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88387. /**
  88388. * Define a task used by {BABYLON.AssetsManager} to load images
  88389. */
  88390. var ImageAssetTask = /** @class */ (function (_super) {
  88391. __extends(ImageAssetTask, _super);
  88392. /**
  88393. * Creates a new ImageAssetTask
  88394. * @param name defines the name of the task
  88395. * @param url defines the location of the image to load
  88396. */
  88397. function ImageAssetTask(
  88398. /**
  88399. * Defines the name of the task
  88400. */
  88401. name,
  88402. /**
  88403. * Defines the location of the image to load
  88404. */
  88405. url) {
  88406. var _this = _super.call(this, name) || this;
  88407. _this.name = name;
  88408. _this.url = url;
  88409. return _this;
  88410. }
  88411. /**
  88412. * Execute the current task
  88413. * @param scene defines the scene where you want your assets to be loaded
  88414. * @param onSuccess is a callback called when the task is successfully executed
  88415. * @param onError is a callback called if an error occurs
  88416. */
  88417. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88418. var _this = this;
  88419. var img = new Image();
  88420. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88421. img.onload = function () {
  88422. _this.image = img;
  88423. onSuccess();
  88424. };
  88425. img.onerror = function (err) {
  88426. onError("Error loading image", err);
  88427. };
  88428. img.src = this.url;
  88429. };
  88430. return ImageAssetTask;
  88431. }(AbstractAssetTask));
  88432. BABYLON.ImageAssetTask = ImageAssetTask;
  88433. /**
  88434. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88435. */
  88436. var TextureAssetTask = /** @class */ (function (_super) {
  88437. __extends(TextureAssetTask, _super);
  88438. /**
  88439. * Creates a new TextureAssetTask object
  88440. * @param name defines the name of the task
  88441. * @param url defines the location of the file to load
  88442. * @param noMipmap defines if mipmap should not be generated (default is false)
  88443. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88444. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88445. */
  88446. function TextureAssetTask(
  88447. /**
  88448. * Defines the name of the task
  88449. */
  88450. name,
  88451. /**
  88452. * Defines the location of the file to load
  88453. */
  88454. url,
  88455. /**
  88456. * Defines if mipmap should not be generated (default is false)
  88457. */
  88458. noMipmap,
  88459. /**
  88460. * Defines if texture must be inverted on Y axis (default is false)
  88461. */
  88462. invertY,
  88463. /**
  88464. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88465. */
  88466. samplingMode) {
  88467. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88468. var _this = _super.call(this, name) || this;
  88469. _this.name = name;
  88470. _this.url = url;
  88471. _this.noMipmap = noMipmap;
  88472. _this.invertY = invertY;
  88473. _this.samplingMode = samplingMode;
  88474. return _this;
  88475. }
  88476. /**
  88477. * Execute the current task
  88478. * @param scene defines the scene where you want your assets to be loaded
  88479. * @param onSuccess is a callback called when the task is successfully executed
  88480. * @param onError is a callback called if an error occurs
  88481. */
  88482. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88483. var onload = function () {
  88484. onSuccess();
  88485. };
  88486. var onerror = function (message, exception) {
  88487. onError(message, exception);
  88488. };
  88489. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88490. };
  88491. return TextureAssetTask;
  88492. }(AbstractAssetTask));
  88493. BABYLON.TextureAssetTask = TextureAssetTask;
  88494. /**
  88495. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88496. */
  88497. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88498. __extends(CubeTextureAssetTask, _super);
  88499. /**
  88500. * Creates a new CubeTextureAssetTask
  88501. * @param name defines the name of the task
  88502. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88503. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88504. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88505. * @param files defines the explicit list of files (undefined by default)
  88506. */
  88507. function CubeTextureAssetTask(
  88508. /**
  88509. * Defines the name of the task
  88510. */
  88511. name,
  88512. /**
  88513. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88514. */
  88515. url,
  88516. /**
  88517. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88518. */
  88519. extensions,
  88520. /**
  88521. * Defines if mipmaps should not be generated (default is false)
  88522. */
  88523. noMipmap,
  88524. /**
  88525. * Defines the explicit list of files (undefined by default)
  88526. */
  88527. files) {
  88528. var _this = _super.call(this, name) || this;
  88529. _this.name = name;
  88530. _this.url = url;
  88531. _this.extensions = extensions;
  88532. _this.noMipmap = noMipmap;
  88533. _this.files = files;
  88534. return _this;
  88535. }
  88536. /**
  88537. * Execute the current task
  88538. * @param scene defines the scene where you want your assets to be loaded
  88539. * @param onSuccess is a callback called when the task is successfully executed
  88540. * @param onError is a callback called if an error occurs
  88541. */
  88542. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88543. var onload = function () {
  88544. onSuccess();
  88545. };
  88546. var onerror = function (message, exception) {
  88547. onError(message, exception);
  88548. };
  88549. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88550. };
  88551. return CubeTextureAssetTask;
  88552. }(AbstractAssetTask));
  88553. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88554. /**
  88555. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88556. */
  88557. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88558. __extends(HDRCubeTextureAssetTask, _super);
  88559. /**
  88560. * Creates a new HDRCubeTextureAssetTask object
  88561. * @param name defines the name of the task
  88562. * @param url defines the location of the file to load
  88563. * @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.
  88564. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88565. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88566. * @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)
  88567. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88568. */
  88569. function HDRCubeTextureAssetTask(
  88570. /**
  88571. * Defines the name of the task
  88572. */
  88573. name,
  88574. /**
  88575. * Defines the location of the file to load
  88576. */
  88577. url,
  88578. /**
  88579. * 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.
  88580. */
  88581. size,
  88582. /**
  88583. * Defines if mipmaps should not be generated (default is false)
  88584. */
  88585. noMipmap,
  88586. /**
  88587. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88588. */
  88589. generateHarmonics,
  88590. /**
  88591. * 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)
  88592. */
  88593. useInGammaSpace,
  88594. /**
  88595. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88596. */
  88597. usePMREMGenerator) {
  88598. if (noMipmap === void 0) { noMipmap = false; }
  88599. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88600. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88601. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88602. var _this = _super.call(this, name) || this;
  88603. _this.name = name;
  88604. _this.url = url;
  88605. _this.size = size;
  88606. _this.noMipmap = noMipmap;
  88607. _this.generateHarmonics = generateHarmonics;
  88608. _this.useInGammaSpace = useInGammaSpace;
  88609. _this.usePMREMGenerator = usePMREMGenerator;
  88610. return _this;
  88611. }
  88612. /**
  88613. * Execute the current task
  88614. * @param scene defines the scene where you want your assets to be loaded
  88615. * @param onSuccess is a callback called when the task is successfully executed
  88616. * @param onError is a callback called if an error occurs
  88617. */
  88618. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88619. var onload = function () {
  88620. onSuccess();
  88621. };
  88622. var onerror = function (message, exception) {
  88623. onError(message, exception);
  88624. };
  88625. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88626. };
  88627. return HDRCubeTextureAssetTask;
  88628. }(AbstractAssetTask));
  88629. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88630. /**
  88631. * This class can be used to easily import assets into a scene
  88632. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88633. */
  88634. var AssetsManager = /** @class */ (function () {
  88635. /**
  88636. * Creates a new AssetsManager
  88637. * @param scene defines the scene to work on
  88638. */
  88639. function AssetsManager(scene) {
  88640. this._isLoading = false;
  88641. this._tasks = new Array();
  88642. this._waitingTasksCount = 0;
  88643. this._totalTasksCount = 0;
  88644. /**
  88645. * Observable called when all tasks are processed
  88646. */
  88647. this.onTaskSuccessObservable = new BABYLON.Observable();
  88648. /**
  88649. * Observable called when a task had an error
  88650. */
  88651. this.onTaskErrorObservable = new BABYLON.Observable();
  88652. /**
  88653. * Observable called when a task is successful
  88654. */
  88655. this.onTasksDoneObservable = new BABYLON.Observable();
  88656. /**
  88657. * Observable called when a task is done (whatever the result is)
  88658. */
  88659. this.onProgressObservable = new BABYLON.Observable();
  88660. /**
  88661. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88662. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88663. */
  88664. this.useDefaultLoadingScreen = true;
  88665. this._scene = scene;
  88666. }
  88667. /**
  88668. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88669. * @param taskName defines the name of the new task
  88670. * @param meshesNames defines the name of meshes to load
  88671. * @param rootUrl defines the root url to use to locate files
  88672. * @param sceneFilename defines the filename of the scene file
  88673. * @returns a new {BABYLON.MeshAssetTask} object
  88674. */
  88675. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88676. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88677. this._tasks.push(task);
  88678. return task;
  88679. };
  88680. /**
  88681. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88682. * @param taskName defines the name of the new task
  88683. * @param url defines the url of the file to load
  88684. * @returns a new {BABYLON.TextFileAssetTask} object
  88685. */
  88686. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88687. var task = new TextFileAssetTask(taskName, url);
  88688. this._tasks.push(task);
  88689. return task;
  88690. };
  88691. /**
  88692. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88693. * @param taskName defines the name of the new task
  88694. * @param url defines the url of the file to load
  88695. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88696. */
  88697. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88698. var task = new BinaryFileAssetTask(taskName, url);
  88699. this._tasks.push(task);
  88700. return task;
  88701. };
  88702. /**
  88703. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88704. * @param taskName defines the name of the new task
  88705. * @param url defines the url of the file to load
  88706. * @returns a new {BABYLON.ImageAssetTask} object
  88707. */
  88708. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88709. var task = new ImageAssetTask(taskName, url);
  88710. this._tasks.push(task);
  88711. return task;
  88712. };
  88713. /**
  88714. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88715. * @param taskName defines the name of the new task
  88716. * @param url defines the url of the file to load
  88717. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88718. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88719. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88720. * @returns a new {BABYLON.TextureAssetTask} object
  88721. */
  88722. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88724. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88725. this._tasks.push(task);
  88726. return task;
  88727. };
  88728. /**
  88729. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88730. * @param taskName defines the name of the new task
  88731. * @param url defines the url of the file to load
  88732. * @param extensions defines the extension to use to load the cube map (can be null)
  88733. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88734. * @param files defines the list of files to load (can be null)
  88735. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88736. */
  88737. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88738. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88739. this._tasks.push(task);
  88740. return task;
  88741. };
  88742. /**
  88743. *
  88744. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88745. * @param taskName defines the name of the new task
  88746. * @param url defines the url of the file to load
  88747. * @param size defines the size you want for the cubemap (can be null)
  88748. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88749. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88750. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88751. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88752. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88753. */
  88754. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88755. if (noMipmap === void 0) { noMipmap = false; }
  88756. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88757. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88758. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88759. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88760. this._tasks.push(task);
  88761. return task;
  88762. };
  88763. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88764. var _this = this;
  88765. this._waitingTasksCount--;
  88766. try {
  88767. if (task.taskState === AssetTaskState.DONE) {
  88768. // Let's remove successfull tasks
  88769. BABYLON.Tools.SetImmediate(function () {
  88770. var index = _this._tasks.indexOf(task);
  88771. if (index > -1) {
  88772. _this._tasks.splice(index, 1);
  88773. }
  88774. });
  88775. }
  88776. if (this.onProgress) {
  88777. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88778. }
  88779. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88780. }
  88781. catch (e) {
  88782. BABYLON.Tools.Error("Error running progress callbacks.");
  88783. console.log(e);
  88784. }
  88785. if (this._waitingTasksCount === 0) {
  88786. try {
  88787. if (this.onFinish) {
  88788. this.onFinish(this._tasks);
  88789. }
  88790. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88791. }
  88792. catch (e) {
  88793. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88794. console.log(e);
  88795. }
  88796. this._isLoading = false;
  88797. this._scene.getEngine().hideLoadingUI();
  88798. }
  88799. };
  88800. AssetsManager.prototype._runTask = function (task) {
  88801. var _this = this;
  88802. var done = function () {
  88803. try {
  88804. if (_this.onTaskSuccess) {
  88805. _this.onTaskSuccess(task);
  88806. }
  88807. _this.onTaskSuccessObservable.notifyObservers(task);
  88808. _this._decreaseWaitingTasksCount(task);
  88809. }
  88810. catch (e) {
  88811. error("Error executing task success callbacks", e);
  88812. }
  88813. };
  88814. var error = function (message, exception) {
  88815. task._setErrorObject(message, exception);
  88816. if (_this.onTaskError) {
  88817. _this.onTaskError(task);
  88818. }
  88819. _this.onTaskErrorObservable.notifyObservers(task);
  88820. _this._decreaseWaitingTasksCount(task);
  88821. };
  88822. task.run(this._scene, done, error);
  88823. };
  88824. /**
  88825. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88826. * @return the current instance of the {BABYLON.AssetsManager}
  88827. */
  88828. AssetsManager.prototype.reset = function () {
  88829. this._isLoading = false;
  88830. this._tasks = new Array();
  88831. return this;
  88832. };
  88833. /**
  88834. * Start the loading process
  88835. * @return the current instance of the {BABYLON.AssetsManager}
  88836. */
  88837. AssetsManager.prototype.load = function () {
  88838. if (this._isLoading) {
  88839. return this;
  88840. }
  88841. this._isLoading = true;
  88842. this._waitingTasksCount = this._tasks.length;
  88843. this._totalTasksCount = this._tasks.length;
  88844. if (this._waitingTasksCount === 0) {
  88845. this._isLoading = false;
  88846. if (this.onFinish) {
  88847. this.onFinish(this._tasks);
  88848. }
  88849. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88850. return this;
  88851. }
  88852. if (this.useDefaultLoadingScreen) {
  88853. this._scene.getEngine().displayLoadingUI();
  88854. }
  88855. for (var index = 0; index < this._tasks.length; index++) {
  88856. var task = this._tasks[index];
  88857. this._runTask(task);
  88858. }
  88859. return this;
  88860. };
  88861. return AssetsManager;
  88862. }());
  88863. BABYLON.AssetsManager = AssetsManager;
  88864. })(BABYLON || (BABYLON = {}));
  88865. //# sourceMappingURL=babylon.assetsManager.js.map
  88866. "use strict";
  88867. var BABYLON;
  88868. (function (BABYLON) {
  88869. var serializedGeometries = [];
  88870. var serializeGeometry = function (geometry, serializationGeometries) {
  88871. if (serializedGeometries[geometry.id]) {
  88872. return;
  88873. }
  88874. if (geometry.doNotSerialize) {
  88875. return;
  88876. }
  88877. if (geometry instanceof BABYLON.BoxGeometry) {
  88878. serializationGeometries.boxes.push(geometry.serialize());
  88879. }
  88880. else if (geometry instanceof BABYLON.SphereGeometry) {
  88881. serializationGeometries.spheres.push(geometry.serialize());
  88882. }
  88883. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88884. serializationGeometries.cylinders.push(geometry.serialize());
  88885. }
  88886. else if (geometry instanceof BABYLON.TorusGeometry) {
  88887. serializationGeometries.toruses.push(geometry.serialize());
  88888. }
  88889. else if (geometry instanceof BABYLON.GroundGeometry) {
  88890. serializationGeometries.grounds.push(geometry.serialize());
  88891. }
  88892. else if (geometry instanceof BABYLON.Plane) {
  88893. serializationGeometries.planes.push(geometry.serialize());
  88894. }
  88895. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88896. serializationGeometries.torusKnots.push(geometry.serialize());
  88897. }
  88898. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88899. throw new Error("Unknown primitive type");
  88900. }
  88901. else {
  88902. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88903. }
  88904. serializedGeometries[geometry.id] = true;
  88905. };
  88906. var serializeMesh = function (mesh, serializationScene) {
  88907. var serializationObject = {};
  88908. // Geometry
  88909. var geometry = mesh._geometry;
  88910. if (geometry) {
  88911. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88912. // 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
  88913. serializeGeometry(geometry, serializationScene.geometries);
  88914. }
  88915. }
  88916. // Custom
  88917. if (mesh.serialize) {
  88918. mesh.serialize(serializationObject);
  88919. }
  88920. return serializationObject;
  88921. };
  88922. var finalizeSingleMesh = function (mesh, serializationObject) {
  88923. //only works if the mesh is already loaded
  88924. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88925. //serialize material
  88926. if (mesh.material) {
  88927. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88928. serializationObject.materials = serializationObject.materials || [];
  88929. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88930. serializationObject.materials.push(mesh.material.serialize());
  88931. }
  88932. }
  88933. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88934. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88935. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88936. serializationObject.multiMaterials.push(mesh.material.serialize());
  88937. }
  88938. }
  88939. }
  88940. //serialize geometry
  88941. var geometry = mesh._geometry;
  88942. if (geometry) {
  88943. if (!serializationObject.geometries) {
  88944. serializationObject.geometries = {};
  88945. serializationObject.geometries.boxes = [];
  88946. serializationObject.geometries.spheres = [];
  88947. serializationObject.geometries.cylinders = [];
  88948. serializationObject.geometries.toruses = [];
  88949. serializationObject.geometries.grounds = [];
  88950. serializationObject.geometries.planes = [];
  88951. serializationObject.geometries.torusKnots = [];
  88952. serializationObject.geometries.vertexData = [];
  88953. }
  88954. serializeGeometry(geometry, serializationObject.geometries);
  88955. }
  88956. // Skeletons
  88957. if (mesh.skeleton) {
  88958. serializationObject.skeletons = serializationObject.skeletons || [];
  88959. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88960. }
  88961. //serialize the actual mesh
  88962. serializationObject.meshes = serializationObject.meshes || [];
  88963. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88964. }
  88965. };
  88966. var SceneSerializer = /** @class */ (function () {
  88967. function SceneSerializer() {
  88968. }
  88969. SceneSerializer.ClearCache = function () {
  88970. serializedGeometries = [];
  88971. };
  88972. SceneSerializer.Serialize = function (scene) {
  88973. var serializationObject = {};
  88974. SceneSerializer.ClearCache();
  88975. // Scene
  88976. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88977. serializationObject.autoClear = scene.autoClear;
  88978. serializationObject.clearColor = scene.clearColor.asArray();
  88979. serializationObject.ambientColor = scene.ambientColor.asArray();
  88980. serializationObject.gravity = scene.gravity.asArray();
  88981. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88982. serializationObject.workerCollisions = scene.workerCollisions;
  88983. // Fog
  88984. if (scene.fogMode && scene.fogMode !== 0) {
  88985. serializationObject.fogMode = scene.fogMode;
  88986. serializationObject.fogColor = scene.fogColor.asArray();
  88987. serializationObject.fogStart = scene.fogStart;
  88988. serializationObject.fogEnd = scene.fogEnd;
  88989. serializationObject.fogDensity = scene.fogDensity;
  88990. }
  88991. //Physics
  88992. if (scene.isPhysicsEnabled()) {
  88993. var physicEngine = scene.getPhysicsEngine();
  88994. if (physicEngine) {
  88995. serializationObject.physicsEnabled = true;
  88996. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88997. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88998. }
  88999. }
  89000. // Metadata
  89001. if (scene.metadata) {
  89002. serializationObject.metadata = scene.metadata;
  89003. }
  89004. // Morph targets
  89005. serializationObject.morphTargetManagers = [];
  89006. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  89007. var abstractMesh = _a[_i];
  89008. var manager = abstractMesh.morphTargetManager;
  89009. if (manager) {
  89010. serializationObject.morphTargetManagers.push(manager.serialize());
  89011. }
  89012. }
  89013. // Lights
  89014. serializationObject.lights = [];
  89015. var index;
  89016. var light;
  89017. for (index = 0; index < scene.lights.length; index++) {
  89018. light = scene.lights[index];
  89019. if (!light.doNotSerialize) {
  89020. serializationObject.lights.push(light.serialize());
  89021. }
  89022. }
  89023. // Cameras
  89024. serializationObject.cameras = [];
  89025. for (index = 0; index < scene.cameras.length; index++) {
  89026. var camera = scene.cameras[index];
  89027. if (!camera.doNotSerialize) {
  89028. serializationObject.cameras.push(camera.serialize());
  89029. }
  89030. }
  89031. if (scene.activeCamera) {
  89032. serializationObject.activeCameraID = scene.activeCamera.id;
  89033. }
  89034. // Animations
  89035. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  89036. // Materials
  89037. serializationObject.materials = [];
  89038. serializationObject.multiMaterials = [];
  89039. var material;
  89040. for (index = 0; index < scene.materials.length; index++) {
  89041. material = scene.materials[index];
  89042. if (!material.doNotSerialize) {
  89043. serializationObject.materials.push(material.serialize());
  89044. }
  89045. }
  89046. // MultiMaterials
  89047. serializationObject.multiMaterials = [];
  89048. for (index = 0; index < scene.multiMaterials.length; index++) {
  89049. var multiMaterial = scene.multiMaterials[index];
  89050. serializationObject.multiMaterials.push(multiMaterial.serialize());
  89051. }
  89052. // Environment texture
  89053. if (scene.environmentTexture) {
  89054. serializationObject.environmentTexture = scene.environmentTexture.name;
  89055. }
  89056. // Skeletons
  89057. serializationObject.skeletons = [];
  89058. for (index = 0; index < scene.skeletons.length; index++) {
  89059. var skeleton = scene.skeletons[index];
  89060. if (!skeleton.doNotSerialize) {
  89061. serializationObject.skeletons.push(skeleton.serialize());
  89062. }
  89063. }
  89064. // Transform nodes
  89065. serializationObject.transformNodes = [];
  89066. for (index = 0; index < scene.transformNodes.length; index++) {
  89067. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  89068. }
  89069. // Geometries
  89070. serializationObject.geometries = {};
  89071. serializationObject.geometries.boxes = [];
  89072. serializationObject.geometries.spheres = [];
  89073. serializationObject.geometries.cylinders = [];
  89074. serializationObject.geometries.toruses = [];
  89075. serializationObject.geometries.grounds = [];
  89076. serializationObject.geometries.planes = [];
  89077. serializationObject.geometries.torusKnots = [];
  89078. serializationObject.geometries.vertexData = [];
  89079. serializedGeometries = [];
  89080. var geometries = scene.getGeometries();
  89081. for (index = 0; index < geometries.length; index++) {
  89082. var geometry = geometries[index];
  89083. if (geometry.isReady()) {
  89084. serializeGeometry(geometry, serializationObject.geometries);
  89085. }
  89086. }
  89087. // Meshes
  89088. serializationObject.meshes = [];
  89089. for (index = 0; index < scene.meshes.length; index++) {
  89090. var abstractMesh = scene.meshes[index];
  89091. if (abstractMesh instanceof BABYLON.Mesh) {
  89092. var mesh = abstractMesh;
  89093. if (!mesh.doNotSerialize) {
  89094. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  89095. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  89096. }
  89097. }
  89098. }
  89099. }
  89100. // Particles Systems
  89101. serializationObject.particleSystems = [];
  89102. for (index = 0; index < scene.particleSystems.length; index++) {
  89103. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  89104. }
  89105. // Lens flares
  89106. serializationObject.lensFlareSystems = [];
  89107. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  89108. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  89109. }
  89110. // Shadows
  89111. serializationObject.shadowGenerators = [];
  89112. for (index = 0; index < scene.lights.length; index++) {
  89113. light = scene.lights[index];
  89114. var shadowGenerator = light.getShadowGenerator();
  89115. if (shadowGenerator) {
  89116. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  89117. }
  89118. }
  89119. // Action Manager
  89120. if (scene.actionManager) {
  89121. serializationObject.actions = scene.actionManager.serialize("scene");
  89122. }
  89123. // Audio
  89124. serializationObject.sounds = [];
  89125. for (index = 0; index < scene.soundTracks.length; index++) {
  89126. var soundtrack = scene.soundTracks[index];
  89127. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  89128. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  89129. }
  89130. }
  89131. return serializationObject;
  89132. };
  89133. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  89134. if (withParents === void 0) { withParents = false; }
  89135. if (withChildren === void 0) { withChildren = false; }
  89136. var serializationObject = {};
  89137. SceneSerializer.ClearCache();
  89138. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  89139. if (withParents || withChildren) {
  89140. //deliberate for loop! not for each, appended should be processed as well.
  89141. for (var i = 0; i < toSerialize.length; ++i) {
  89142. if (withChildren) {
  89143. toSerialize[i].getDescendants().forEach(function (node) {
  89144. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  89145. toSerialize.push(node);
  89146. }
  89147. });
  89148. }
  89149. //make sure the array doesn't contain the object already
  89150. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  89151. toSerialize.push(toSerialize[i].parent);
  89152. }
  89153. }
  89154. }
  89155. toSerialize.forEach(function (mesh) {
  89156. finalizeSingleMesh(mesh, serializationObject);
  89157. });
  89158. return serializationObject;
  89159. };
  89160. return SceneSerializer;
  89161. }());
  89162. BABYLON.SceneSerializer = SceneSerializer;
  89163. })(BABYLON || (BABYLON = {}));
  89164. //# sourceMappingURL=babylon.sceneSerializer.js.map
  89165. "use strict";
  89166. var BABYLON;
  89167. (function (BABYLON) {
  89168. var ReflectionProbe = /** @class */ (function () {
  89169. function ReflectionProbe(name, size, scene, generateMipMaps) {
  89170. if (generateMipMaps === void 0) { generateMipMaps = true; }
  89171. var _this = this;
  89172. this.name = name;
  89173. this._viewMatrix = BABYLON.Matrix.Identity();
  89174. this._target = BABYLON.Vector3.Zero();
  89175. this._add = BABYLON.Vector3.Zero();
  89176. this._invertYAxis = false;
  89177. this.position = BABYLON.Vector3.Zero();
  89178. this._scene = scene;
  89179. this._scene.reflectionProbes.push(this);
  89180. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  89181. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  89182. switch (faceIndex) {
  89183. case 0:
  89184. _this._add.copyFromFloats(1, 0, 0);
  89185. break;
  89186. case 1:
  89187. _this._add.copyFromFloats(-1, 0, 0);
  89188. break;
  89189. case 2:
  89190. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  89191. break;
  89192. case 3:
  89193. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  89194. break;
  89195. case 4:
  89196. _this._add.copyFromFloats(0, 0, 1);
  89197. break;
  89198. case 5:
  89199. _this._add.copyFromFloats(0, 0, -1);
  89200. break;
  89201. }
  89202. if (_this._attachedMesh) {
  89203. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  89204. }
  89205. _this.position.addToRef(_this._add, _this._target);
  89206. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  89207. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  89208. scene._forcedViewPosition = _this.position;
  89209. });
  89210. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  89211. scene._forcedViewPosition = null;
  89212. scene.updateTransformMatrix(true);
  89213. });
  89214. if (scene.activeCamera) {
  89215. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  89216. }
  89217. }
  89218. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  89219. get: function () {
  89220. return this._renderTargetTexture.samples;
  89221. },
  89222. set: function (value) {
  89223. this._renderTargetTexture.samples = value;
  89224. },
  89225. enumerable: true,
  89226. configurable: true
  89227. });
  89228. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  89229. get: function () {
  89230. return this._renderTargetTexture.refreshRate;
  89231. },
  89232. set: function (value) {
  89233. this._renderTargetTexture.refreshRate = value;
  89234. },
  89235. enumerable: true,
  89236. configurable: true
  89237. });
  89238. ReflectionProbe.prototype.getScene = function () {
  89239. return this._scene;
  89240. };
  89241. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  89242. get: function () {
  89243. return this._renderTargetTexture;
  89244. },
  89245. enumerable: true,
  89246. configurable: true
  89247. });
  89248. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  89249. get: function () {
  89250. return this._renderTargetTexture.renderList;
  89251. },
  89252. enumerable: true,
  89253. configurable: true
  89254. });
  89255. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  89256. this._attachedMesh = mesh;
  89257. };
  89258. /**
  89259. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  89260. *
  89261. * @param renderingGroupId The rendering group id corresponding to its index
  89262. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  89263. */
  89264. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  89265. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  89266. };
  89267. ReflectionProbe.prototype.dispose = function () {
  89268. var index = this._scene.reflectionProbes.indexOf(this);
  89269. if (index !== -1) {
  89270. // Remove from the scene if found
  89271. this._scene.reflectionProbes.splice(index, 1);
  89272. }
  89273. if (this._renderTargetTexture) {
  89274. this._renderTargetTexture.dispose();
  89275. this._renderTargetTexture = null;
  89276. }
  89277. };
  89278. return ReflectionProbe;
  89279. }());
  89280. BABYLON.ReflectionProbe = ReflectionProbe;
  89281. })(BABYLON || (BABYLON = {}));
  89282. //# sourceMappingURL=babylon.reflectionProbe.js.map
  89283. "use strict";
  89284. var BABYLON;
  89285. (function (BABYLON) {
  89286. var Layer = /** @class */ (function () {
  89287. function Layer(name, imgUrl, scene, isBackground, color) {
  89288. this.name = name;
  89289. this.scale = new BABYLON.Vector2(1, 1);
  89290. this.offset = new BABYLON.Vector2(0, 0);
  89291. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  89292. this.layerMask = 0x0FFFFFFF;
  89293. this._vertexBuffers = {};
  89294. // Events
  89295. /**
  89296. * An event triggered when the layer is disposed.
  89297. */
  89298. this.onDisposeObservable = new BABYLON.Observable();
  89299. /**
  89300. * An event triggered before rendering the scene
  89301. */
  89302. this.onBeforeRenderObservable = new BABYLON.Observable();
  89303. /**
  89304. * An event triggered after rendering the scene
  89305. */
  89306. this.onAfterRenderObservable = new BABYLON.Observable();
  89307. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  89308. this.isBackground = isBackground === undefined ? true : isBackground;
  89309. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  89310. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  89311. this._scene.layers.push(this);
  89312. var engine = this._scene.getEngine();
  89313. // VBO
  89314. var vertices = [];
  89315. vertices.push(1, 1);
  89316. vertices.push(-1, 1);
  89317. vertices.push(-1, -1);
  89318. vertices.push(1, -1);
  89319. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89320. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89321. this._createIndexBuffer();
  89322. // Effects
  89323. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  89324. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  89325. }
  89326. Object.defineProperty(Layer.prototype, "onDispose", {
  89327. set: function (callback) {
  89328. if (this._onDisposeObserver) {
  89329. this.onDisposeObservable.remove(this._onDisposeObserver);
  89330. }
  89331. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89332. },
  89333. enumerable: true,
  89334. configurable: true
  89335. });
  89336. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  89337. set: function (callback) {
  89338. if (this._onBeforeRenderObserver) {
  89339. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  89340. }
  89341. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  89342. },
  89343. enumerable: true,
  89344. configurable: true
  89345. });
  89346. Object.defineProperty(Layer.prototype, "onAfterRender", {
  89347. set: function (callback) {
  89348. if (this._onAfterRenderObserver) {
  89349. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89350. }
  89351. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89352. },
  89353. enumerable: true,
  89354. configurable: true
  89355. });
  89356. Layer.prototype._createIndexBuffer = function () {
  89357. var engine = this._scene.getEngine();
  89358. // Indices
  89359. var indices = [];
  89360. indices.push(0);
  89361. indices.push(1);
  89362. indices.push(2);
  89363. indices.push(0);
  89364. indices.push(2);
  89365. indices.push(3);
  89366. this._indexBuffer = engine.createIndexBuffer(indices);
  89367. };
  89368. Layer.prototype._rebuild = function () {
  89369. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89370. if (vb) {
  89371. vb._rebuild();
  89372. }
  89373. this._createIndexBuffer();
  89374. };
  89375. Layer.prototype.render = function () {
  89376. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89377. // Check
  89378. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89379. return;
  89380. var engine = this._scene.getEngine();
  89381. this.onBeforeRenderObservable.notifyObservers(this);
  89382. // Render
  89383. engine.enableEffect(currentEffect);
  89384. engine.setState(false);
  89385. // Texture
  89386. currentEffect.setTexture("textureSampler", this.texture);
  89387. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89388. // Color
  89389. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89390. // Scale / offset
  89391. currentEffect.setVector2("offset", this.offset);
  89392. currentEffect.setVector2("scale", this.scale);
  89393. // VBOs
  89394. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89395. // Draw order
  89396. if (!this.alphaTest) {
  89397. engine.setAlphaMode(this.alphaBlendingMode);
  89398. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89399. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89400. }
  89401. else {
  89402. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89403. }
  89404. this.onAfterRenderObservable.notifyObservers(this);
  89405. };
  89406. Layer.prototype.dispose = function () {
  89407. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89408. if (vertexBuffer) {
  89409. vertexBuffer.dispose();
  89410. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89411. }
  89412. if (this._indexBuffer) {
  89413. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89414. this._indexBuffer = null;
  89415. }
  89416. if (this.texture) {
  89417. this.texture.dispose();
  89418. this.texture = null;
  89419. }
  89420. // Remove from scene
  89421. var index = this._scene.layers.indexOf(this);
  89422. this._scene.layers.splice(index, 1);
  89423. // Callback
  89424. this.onDisposeObservable.notifyObservers(this);
  89425. this.onDisposeObservable.clear();
  89426. this.onAfterRenderObservable.clear();
  89427. this.onBeforeRenderObservable.clear();
  89428. };
  89429. return Layer;
  89430. }());
  89431. BABYLON.Layer = Layer;
  89432. })(BABYLON || (BABYLON = {}));
  89433. //# sourceMappingURL=babylon.layer.js.map
  89434. "use strict";
  89435. var BABYLON;
  89436. (function (BABYLON) {
  89437. var TextureTools = /** @class */ (function () {
  89438. function TextureTools() {
  89439. }
  89440. /**
  89441. * Uses the GPU to create a copy texture rescaled at a given size
  89442. * @param texture Texture to copy from
  89443. * @param width Desired width
  89444. * @param height Desired height
  89445. * @return Generated texture
  89446. */
  89447. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89448. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89449. var scene = texture.getScene();
  89450. var engine = scene.getEngine();
  89451. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89452. rtt.wrapU = texture.wrapU;
  89453. rtt.wrapV = texture.wrapV;
  89454. rtt.uOffset = texture.uOffset;
  89455. rtt.vOffset = texture.vOffset;
  89456. rtt.uScale = texture.uScale;
  89457. rtt.vScale = texture.vScale;
  89458. rtt.uAng = texture.uAng;
  89459. rtt.vAng = texture.vAng;
  89460. rtt.wAng = texture.wAng;
  89461. rtt.coordinatesIndex = texture.coordinatesIndex;
  89462. rtt.level = texture.level;
  89463. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89464. rtt._texture.isReady = false;
  89465. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89466. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89467. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89468. passPostProcess.getEffect().executeWhenCompiled(function () {
  89469. passPostProcess.onApply = function (effect) {
  89470. effect.setTexture("textureSampler", texture);
  89471. };
  89472. var internalTexture = rtt.getInternalTexture();
  89473. if (internalTexture) {
  89474. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89475. engine.unBindFramebuffer(internalTexture);
  89476. rtt.disposeFramebufferObjects();
  89477. passPostProcess.dispose();
  89478. internalTexture.isReady = true;
  89479. }
  89480. });
  89481. return rtt;
  89482. };
  89483. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89484. if (!scene._environmentBRDFTexture) {
  89485. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89486. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89487. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89488. scene._environmentBRDFTexture = texture;
  89489. }
  89490. return scene._environmentBRDFTexture;
  89491. };
  89492. 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=";
  89493. return TextureTools;
  89494. }());
  89495. BABYLON.TextureTools = TextureTools;
  89496. })(BABYLON || (BABYLON = {}));
  89497. //# sourceMappingURL=babylon.textureTools.js.map
  89498. "use strict";
  89499. var BABYLON;
  89500. (function (BABYLON) {
  89501. var FramingBehavior = /** @class */ (function () {
  89502. function FramingBehavior() {
  89503. this._mode = FramingBehavior.FitFrustumSidesMode;
  89504. this._radiusScale = 1.0;
  89505. this._positionScale = 0.5;
  89506. this._defaultElevation = 0.3;
  89507. this._elevationReturnTime = 1500;
  89508. this._elevationReturnWaitTime = 1000;
  89509. this._zoomStopsAnimation = false;
  89510. this._framingTime = 1500;
  89511. this._isPointerDown = false;
  89512. this._lastInteractionTime = -Infinity;
  89513. // Framing control
  89514. this._animatables = new Array();
  89515. this._betaIsAnimating = false;
  89516. }
  89517. Object.defineProperty(FramingBehavior.prototype, "name", {
  89518. get: function () {
  89519. return "Framing";
  89520. },
  89521. enumerable: true,
  89522. configurable: true
  89523. });
  89524. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89525. /**
  89526. * Gets current mode used by the behavior.
  89527. */
  89528. get: function () {
  89529. return this._mode;
  89530. },
  89531. /**
  89532. * Sets the current mode used by the behavior
  89533. */
  89534. set: function (mode) {
  89535. this._mode = mode;
  89536. },
  89537. enumerable: true,
  89538. configurable: true
  89539. });
  89540. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89541. /**
  89542. * Gets the scale applied to the radius
  89543. */
  89544. get: function () {
  89545. return this._radiusScale;
  89546. },
  89547. /**
  89548. * Sets the scale applied to the radius (1 by default)
  89549. */
  89550. set: function (radius) {
  89551. this._radiusScale = radius;
  89552. },
  89553. enumerable: true,
  89554. configurable: true
  89555. });
  89556. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89557. /**
  89558. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89559. */
  89560. get: function () {
  89561. return this._positionScale;
  89562. },
  89563. /**
  89564. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89565. */
  89566. set: function (scale) {
  89567. this._positionScale = scale;
  89568. },
  89569. enumerable: true,
  89570. configurable: true
  89571. });
  89572. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89573. /**
  89574. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89575. * behaviour is triggered, in radians.
  89576. */
  89577. get: function () {
  89578. return this._defaultElevation;
  89579. },
  89580. /**
  89581. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89582. * behaviour is triggered, in radians.
  89583. */
  89584. set: function (elevation) {
  89585. this._defaultElevation = elevation;
  89586. },
  89587. enumerable: true,
  89588. configurable: true
  89589. });
  89590. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89591. /**
  89592. * Gets the time (in milliseconds) taken to return to the default beta position.
  89593. * Negative value indicates camera should not return to default.
  89594. */
  89595. get: function () {
  89596. return this._elevationReturnTime;
  89597. },
  89598. /**
  89599. * Sets the time (in milliseconds) taken to return to the default beta position.
  89600. * Negative value indicates camera should not return to default.
  89601. */
  89602. set: function (speed) {
  89603. this._elevationReturnTime = speed;
  89604. },
  89605. enumerable: true,
  89606. configurable: true
  89607. });
  89608. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89609. /**
  89610. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89611. */
  89612. get: function () {
  89613. return this._elevationReturnWaitTime;
  89614. },
  89615. /**
  89616. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89617. */
  89618. set: function (time) {
  89619. this._elevationReturnWaitTime = time;
  89620. },
  89621. enumerable: true,
  89622. configurable: true
  89623. });
  89624. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89625. /**
  89626. * Gets the flag that indicates if user zooming should stop animation.
  89627. */
  89628. get: function () {
  89629. return this._zoomStopsAnimation;
  89630. },
  89631. /**
  89632. * Sets the flag that indicates if user zooming should stop animation.
  89633. */
  89634. set: function (flag) {
  89635. this._zoomStopsAnimation = flag;
  89636. },
  89637. enumerable: true,
  89638. configurable: true
  89639. });
  89640. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89641. /**
  89642. * Gets the transition time when framing the mesh, in milliseconds
  89643. */
  89644. get: function () {
  89645. return this._framingTime;
  89646. },
  89647. /**
  89648. * Sets the transition time when framing the mesh, in milliseconds
  89649. */
  89650. set: function (time) {
  89651. this._framingTime = time;
  89652. },
  89653. enumerable: true,
  89654. configurable: true
  89655. });
  89656. FramingBehavior.prototype.init = function () {
  89657. // Do notihng
  89658. };
  89659. FramingBehavior.prototype.attach = function (camera) {
  89660. var _this = this;
  89661. this._attachedCamera = camera;
  89662. var scene = this._attachedCamera.getScene();
  89663. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89664. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89665. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89666. _this._isPointerDown = true;
  89667. return;
  89668. }
  89669. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89670. _this._isPointerDown = false;
  89671. }
  89672. });
  89673. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89674. if (mesh) {
  89675. _this.zoomOnMesh(mesh);
  89676. }
  89677. });
  89678. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89679. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89680. _this._applyUserInteraction();
  89681. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89682. // back to the default position after a given timeout
  89683. _this._maintainCameraAboveGround();
  89684. });
  89685. };
  89686. FramingBehavior.prototype.detach = function () {
  89687. if (!this._attachedCamera) {
  89688. return;
  89689. }
  89690. var scene = this._attachedCamera.getScene();
  89691. if (this._onPrePointerObservableObserver) {
  89692. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89693. }
  89694. if (this._onAfterCheckInputsObserver) {
  89695. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89696. }
  89697. if (this._onMeshTargetChangedObserver) {
  89698. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89699. }
  89700. this._attachedCamera = null;
  89701. };
  89702. /**
  89703. * Targets the given mesh and updates zoom level accordingly.
  89704. * @param mesh The mesh to target.
  89705. * @param radius Optional. If a cached radius position already exists, overrides default.
  89706. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89707. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89708. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89709. */
  89710. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89711. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89712. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89713. mesh.computeWorldMatrix(true);
  89714. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89715. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89716. };
  89717. /**
  89718. * Targets the given mesh with its children and updates zoom level accordingly.
  89719. * @param mesh The mesh to target.
  89720. * @param radius Optional. If a cached radius position already exists, overrides default.
  89721. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89722. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89723. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89724. */
  89725. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89726. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89727. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89728. mesh.computeWorldMatrix(true);
  89729. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89730. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89731. };
  89732. /**
  89733. * Targets the given meshes with their children and updates zoom level accordingly.
  89734. * @param meshes The mesh to target.
  89735. * @param radius Optional. If a cached radius position already exists, overrides default.
  89736. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89737. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89738. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89739. */
  89740. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89741. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89742. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89743. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89744. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89745. for (var i = 0; i < meshes.length; i++) {
  89746. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89747. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89748. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89749. }
  89750. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89751. };
  89752. /**
  89753. * Targets the given mesh and updates zoom level accordingly.
  89754. * @param mesh The mesh to target.
  89755. * @param radius Optional. If a cached radius position already exists, overrides default.
  89756. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89757. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89758. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89759. */
  89760. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89761. var _this = this;
  89762. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89763. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89764. var zoomTarget;
  89765. if (!this._attachedCamera) {
  89766. return;
  89767. }
  89768. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89769. var bottom = minimumWorld.y;
  89770. var top = maximumWorld.y;
  89771. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89772. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89773. if (focusOnOriginXZ) {
  89774. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89775. }
  89776. else {
  89777. var centerWorld = minimumWorld.add(radiusWorld);
  89778. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89779. }
  89780. if (!this._vectorTransition) {
  89781. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89782. }
  89783. this._betaIsAnimating = true;
  89784. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89785. if (animatable) {
  89786. this._animatables.push(animatable);
  89787. }
  89788. // sets the radius and lower radius bounds
  89789. // Small delta ensures camera is not always at lower zoom limit.
  89790. var radius = 0;
  89791. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89792. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89793. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89794. radius = position;
  89795. }
  89796. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89797. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89798. if (this._attachedCamera.lowerRadiusLimit === null) {
  89799. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89800. }
  89801. }
  89802. // Set sensibilities
  89803. var extend = maximumWorld.subtract(minimumWorld).length();
  89804. this._attachedCamera.panningSensibility = 5000 / extend;
  89805. this._attachedCamera.wheelPrecision = 100 / radius;
  89806. // transition to new radius
  89807. if (!this._radiusTransition) {
  89808. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89809. }
  89810. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89811. _this.stopAllAnimations();
  89812. if (onAnimationEnd) {
  89813. onAnimationEnd();
  89814. }
  89815. if (_this._attachedCamera) {
  89816. _this._attachedCamera.storeState();
  89817. }
  89818. });
  89819. if (animatable) {
  89820. this._animatables.push(animatable);
  89821. }
  89822. };
  89823. /**
  89824. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89825. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89826. * frustum width.
  89827. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89828. * to fully enclose the mesh in the viewing frustum.
  89829. */
  89830. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89831. var size = maximumWorld.subtract(minimumWorld);
  89832. var boxVectorGlobalDiagonal = size.length();
  89833. var frustumSlope = this._getFrustumSlope();
  89834. // Formula for setting distance
  89835. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89836. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89837. // Horizon distance
  89838. var radius = radiusWithoutFraming * this._radiusScale;
  89839. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89840. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89841. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89842. var camera = this._attachedCamera;
  89843. if (!camera) {
  89844. return 0;
  89845. }
  89846. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89847. // Don't exceed the requested limit
  89848. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89849. }
  89850. // Don't exceed the upper radius limit
  89851. if (camera.upperRadiusLimit) {
  89852. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89853. }
  89854. return distance;
  89855. };
  89856. /**
  89857. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89858. * is automatically returned to its default position (expected to be above ground plane).
  89859. */
  89860. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89861. var _this = this;
  89862. if (this._elevationReturnTime < 0) {
  89863. return;
  89864. }
  89865. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89866. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89867. var limitBeta = Math.PI * 0.5;
  89868. // Bring the camera back up if below the ground plane
  89869. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89870. this._betaIsAnimating = true;
  89871. //Transition to new position
  89872. this.stopAllAnimations();
  89873. if (!this._betaTransition) {
  89874. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89875. }
  89876. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89877. _this._clearAnimationLocks();
  89878. _this.stopAllAnimations();
  89879. });
  89880. if (animatabe) {
  89881. this._animatables.push(animatabe);
  89882. }
  89883. }
  89884. };
  89885. /**
  89886. * Returns the frustum slope based on the canvas ratio and camera FOV
  89887. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89888. */
  89889. FramingBehavior.prototype._getFrustumSlope = function () {
  89890. // Calculate the viewport ratio
  89891. // Aspect Ratio is Height/Width.
  89892. var camera = this._attachedCamera;
  89893. if (!camera) {
  89894. return BABYLON.Vector2.Zero();
  89895. }
  89896. var engine = camera.getScene().getEngine();
  89897. var aspectRatio = engine.getAspectRatio(camera);
  89898. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89899. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89900. var frustumSlopeY = Math.tan(camera.fov / 2);
  89901. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89902. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89903. // along the forward vector.
  89904. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89905. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89906. };
  89907. /**
  89908. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89909. */
  89910. FramingBehavior.prototype._clearAnimationLocks = function () {
  89911. this._betaIsAnimating = false;
  89912. };
  89913. /**
  89914. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89915. */
  89916. FramingBehavior.prototype._applyUserInteraction = function () {
  89917. if (this.isUserIsMoving) {
  89918. this._lastInteractionTime = BABYLON.Tools.Now;
  89919. this.stopAllAnimations();
  89920. this._clearAnimationLocks();
  89921. }
  89922. };
  89923. /**
  89924. * Stops and removes all animations that have been applied to the camera
  89925. */
  89926. FramingBehavior.prototype.stopAllAnimations = function () {
  89927. if (this._attachedCamera) {
  89928. this._attachedCamera.animations = [];
  89929. }
  89930. while (this._animatables.length) {
  89931. if (this._animatables[0]) {
  89932. this._animatables[0].onAnimationEnd = null;
  89933. this._animatables[0].stop();
  89934. }
  89935. this._animatables.shift();
  89936. }
  89937. };
  89938. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89939. /**
  89940. * Gets a value indicating if the user is moving the camera
  89941. */
  89942. get: function () {
  89943. if (!this._attachedCamera) {
  89944. return false;
  89945. }
  89946. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89947. this._attachedCamera.inertialBetaOffset !== 0 ||
  89948. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89949. this._attachedCamera.inertialPanningX !== 0 ||
  89950. this._attachedCamera.inertialPanningY !== 0 ||
  89951. this._isPointerDown;
  89952. },
  89953. enumerable: true,
  89954. configurable: true
  89955. });
  89956. /**
  89957. * The easing function used by animations
  89958. */
  89959. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89960. /**
  89961. * The easing mode used by animations
  89962. */
  89963. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89964. // Statics
  89965. /**
  89966. * The camera can move all the way towards the mesh.
  89967. */
  89968. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89969. /**
  89970. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89971. */
  89972. FramingBehavior.FitFrustumSidesMode = 1;
  89973. return FramingBehavior;
  89974. }());
  89975. BABYLON.FramingBehavior = FramingBehavior;
  89976. })(BABYLON || (BABYLON = {}));
  89977. //# sourceMappingURL=babylon.framingBehavior.js.map
  89978. "use strict";
  89979. var BABYLON;
  89980. (function (BABYLON) {
  89981. /**
  89982. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89983. */
  89984. var BouncingBehavior = /** @class */ (function () {
  89985. function BouncingBehavior() {
  89986. /**
  89987. * The duration of the animation, in milliseconds
  89988. */
  89989. this.transitionDuration = 450;
  89990. /**
  89991. * Length of the distance animated by the transition when lower radius is reached
  89992. */
  89993. this.lowerRadiusTransitionRange = 2;
  89994. /**
  89995. * Length of the distance animated by the transition when upper radius is reached
  89996. */
  89997. this.upperRadiusTransitionRange = -2;
  89998. this._autoTransitionRange = false;
  89999. // Animations
  90000. this._radiusIsAnimating = false;
  90001. this._radiusBounceTransition = null;
  90002. this._animatables = new Array();
  90003. }
  90004. Object.defineProperty(BouncingBehavior.prototype, "name", {
  90005. get: function () {
  90006. return "Bouncing";
  90007. },
  90008. enumerable: true,
  90009. configurable: true
  90010. });
  90011. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  90012. /**
  90013. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  90014. */
  90015. get: function () {
  90016. return this._autoTransitionRange;
  90017. },
  90018. /**
  90019. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  90020. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  90021. */
  90022. set: function (value) {
  90023. var _this = this;
  90024. if (this._autoTransitionRange === value) {
  90025. return;
  90026. }
  90027. this._autoTransitionRange = value;
  90028. var camera = this._attachedCamera;
  90029. if (!camera) {
  90030. return;
  90031. }
  90032. if (value) {
  90033. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  90034. if (!mesh) {
  90035. return;
  90036. }
  90037. mesh.computeWorldMatrix(true);
  90038. var diagonal = mesh.getBoundingInfo().diagonalLength;
  90039. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  90040. _this.upperRadiusTransitionRange = diagonal * 0.05;
  90041. });
  90042. }
  90043. else if (this._onMeshTargetChangedObserver) {
  90044. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  90045. }
  90046. },
  90047. enumerable: true,
  90048. configurable: true
  90049. });
  90050. BouncingBehavior.prototype.init = function () {
  90051. // Do notihng
  90052. };
  90053. BouncingBehavior.prototype.attach = function (camera) {
  90054. var _this = this;
  90055. this._attachedCamera = camera;
  90056. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  90057. if (!_this._attachedCamera) {
  90058. return;
  90059. }
  90060. // Add the bounce animation to the lower radius limit
  90061. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  90062. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  90063. }
  90064. // Add the bounce animation to the upper radius limit
  90065. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  90066. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  90067. }
  90068. });
  90069. };
  90070. BouncingBehavior.prototype.detach = function () {
  90071. if (!this._attachedCamera) {
  90072. return;
  90073. }
  90074. if (this._onAfterCheckInputsObserver) {
  90075. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  90076. }
  90077. if (this._onMeshTargetChangedObserver) {
  90078. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  90079. }
  90080. this._attachedCamera = null;
  90081. };
  90082. /**
  90083. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  90084. * @param radiusLimit The limit to check against.
  90085. * @return Bool to indicate if at limit.
  90086. */
  90087. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  90088. if (!this._attachedCamera) {
  90089. return false;
  90090. }
  90091. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  90092. return true;
  90093. }
  90094. return false;
  90095. };
  90096. /**
  90097. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  90098. * @param radiusDelta The delta by which to animate to. Can be negative.
  90099. */
  90100. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  90101. var _this = this;
  90102. if (!this._attachedCamera) {
  90103. return;
  90104. }
  90105. if (!this._radiusBounceTransition) {
  90106. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  90107. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  90108. }
  90109. // Prevent zoom until bounce has completed
  90110. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  90111. this._attachedCamera.wheelPrecision = Infinity;
  90112. this._attachedCamera.inertialRadiusOffset = 0;
  90113. // Animate to the radius limit
  90114. this.stopAllAnimations();
  90115. this._radiusIsAnimating = true;
  90116. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  90117. if (animatable) {
  90118. this._animatables.push(animatable);
  90119. }
  90120. };
  90121. /**
  90122. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  90123. */
  90124. BouncingBehavior.prototype._clearAnimationLocks = function () {
  90125. this._radiusIsAnimating = false;
  90126. if (this._attachedCamera) {
  90127. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  90128. }
  90129. };
  90130. /**
  90131. * Stops and removes all animations that have been applied to the camera
  90132. */
  90133. BouncingBehavior.prototype.stopAllAnimations = function () {
  90134. if (this._attachedCamera) {
  90135. this._attachedCamera.animations = [];
  90136. }
  90137. while (this._animatables.length) {
  90138. this._animatables[0].onAnimationEnd = null;
  90139. this._animatables[0].stop();
  90140. this._animatables.shift();
  90141. }
  90142. };
  90143. /**
  90144. * The easing function used by animations
  90145. */
  90146. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  90147. /**
  90148. * The easing mode used by animations
  90149. */
  90150. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  90151. return BouncingBehavior;
  90152. }());
  90153. BABYLON.BouncingBehavior = BouncingBehavior;
  90154. })(BABYLON || (BABYLON = {}));
  90155. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  90156. "use strict";
  90157. var BABYLON;
  90158. (function (BABYLON) {
  90159. var AutoRotationBehavior = /** @class */ (function () {
  90160. function AutoRotationBehavior() {
  90161. this._zoomStopsAnimation = false;
  90162. this._idleRotationSpeed = 0.05;
  90163. this._idleRotationWaitTime = 2000;
  90164. this._idleRotationSpinupTime = 2000;
  90165. this._isPointerDown = false;
  90166. this._lastFrameTime = null;
  90167. this._lastInteractionTime = -Infinity;
  90168. this._cameraRotationSpeed = 0;
  90169. this._lastFrameRadius = 0;
  90170. }
  90171. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  90172. get: function () {
  90173. return "AutoRotation";
  90174. },
  90175. enumerable: true,
  90176. configurable: true
  90177. });
  90178. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  90179. /**
  90180. * Gets the flag that indicates if user zooming should stop animation.
  90181. */
  90182. get: function () {
  90183. return this._zoomStopsAnimation;
  90184. },
  90185. /**
  90186. * Sets the flag that indicates if user zooming should stop animation.
  90187. */
  90188. set: function (flag) {
  90189. this._zoomStopsAnimation = flag;
  90190. },
  90191. enumerable: true,
  90192. configurable: true
  90193. });
  90194. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  90195. /**
  90196. * Gets the default speed at which the camera rotates around the model.
  90197. */
  90198. get: function () {
  90199. return this._idleRotationSpeed;
  90200. },
  90201. /**
  90202. * Sets the default speed at which the camera rotates around the model.
  90203. */
  90204. set: function (speed) {
  90205. this._idleRotationSpeed = speed;
  90206. },
  90207. enumerable: true,
  90208. configurable: true
  90209. });
  90210. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  90211. /**
  90212. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  90213. */
  90214. get: function () {
  90215. return this._idleRotationWaitTime;
  90216. },
  90217. /**
  90218. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  90219. */
  90220. set: function (time) {
  90221. this._idleRotationWaitTime = time;
  90222. },
  90223. enumerable: true,
  90224. configurable: true
  90225. });
  90226. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  90227. /**
  90228. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90229. */
  90230. get: function () {
  90231. return this._idleRotationSpinupTime;
  90232. },
  90233. /**
  90234. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90235. */
  90236. set: function (time) {
  90237. this._idleRotationSpinupTime = time;
  90238. },
  90239. enumerable: true,
  90240. configurable: true
  90241. });
  90242. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  90243. /**
  90244. * Gets a value indicating if the camera is currently rotating because of this behavior
  90245. */
  90246. get: function () {
  90247. return Math.abs(this._cameraRotationSpeed) > 0;
  90248. },
  90249. enumerable: true,
  90250. configurable: true
  90251. });
  90252. AutoRotationBehavior.prototype.init = function () {
  90253. // Do notihng
  90254. };
  90255. AutoRotationBehavior.prototype.attach = function (camera) {
  90256. var _this = this;
  90257. this._attachedCamera = camera;
  90258. var scene = this._attachedCamera.getScene();
  90259. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  90260. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90261. _this._isPointerDown = true;
  90262. return;
  90263. }
  90264. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  90265. _this._isPointerDown = false;
  90266. }
  90267. });
  90268. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  90269. var now = BABYLON.Tools.Now;
  90270. var dt = 0;
  90271. if (_this._lastFrameTime != null) {
  90272. dt = now - _this._lastFrameTime;
  90273. }
  90274. _this._lastFrameTime = now;
  90275. // Stop the animation if there is user interaction and the animation should stop for this interaction
  90276. _this._applyUserInteraction();
  90277. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  90278. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  90279. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  90280. // Step camera rotation by rotation speed
  90281. if (_this._attachedCamera) {
  90282. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  90283. }
  90284. });
  90285. };
  90286. AutoRotationBehavior.prototype.detach = function () {
  90287. if (!this._attachedCamera) {
  90288. return;
  90289. }
  90290. var scene = this._attachedCamera.getScene();
  90291. if (this._onPrePointerObservableObserver) {
  90292. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  90293. }
  90294. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  90295. this._attachedCamera = null;
  90296. };
  90297. /**
  90298. * Returns true if user is scrolling.
  90299. * @return true if user is scrolling.
  90300. */
  90301. AutoRotationBehavior.prototype._userIsZooming = function () {
  90302. if (!this._attachedCamera) {
  90303. return false;
  90304. }
  90305. return this._attachedCamera.inertialRadiusOffset !== 0;
  90306. };
  90307. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  90308. if (!this._attachedCamera) {
  90309. return false;
  90310. }
  90311. var zoomHasHitLimit = false;
  90312. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  90313. zoomHasHitLimit = true;
  90314. }
  90315. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  90316. this._lastFrameRadius = this._attachedCamera.radius;
  90317. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  90318. };
  90319. /**
  90320. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  90321. */
  90322. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  90323. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  90324. this._lastInteractionTime = BABYLON.Tools.Now;
  90325. }
  90326. };
  90327. // Tools
  90328. AutoRotationBehavior.prototype._userIsMoving = function () {
  90329. if (!this._attachedCamera) {
  90330. return false;
  90331. }
  90332. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90333. this._attachedCamera.inertialBetaOffset !== 0 ||
  90334. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90335. this._attachedCamera.inertialPanningX !== 0 ||
  90336. this._attachedCamera.inertialPanningY !== 0 ||
  90337. this._isPointerDown;
  90338. };
  90339. return AutoRotationBehavior;
  90340. }());
  90341. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  90342. })(BABYLON || (BABYLON = {}));
  90343. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  90344. "use strict";
  90345. var BABYLON;
  90346. (function (BABYLON) {
  90347. var NullEngineOptions = /** @class */ (function () {
  90348. function NullEngineOptions() {
  90349. this.renderWidth = 512;
  90350. this.renderHeight = 256;
  90351. this.textureSize = 512;
  90352. this.deterministicLockstep = false;
  90353. this.lockstepMaxSteps = 4;
  90354. }
  90355. return NullEngineOptions;
  90356. }());
  90357. BABYLON.NullEngineOptions = NullEngineOptions;
  90358. /**
  90359. * The null engine class provides support for headless version of babylon.js.
  90360. * This can be used in server side scenario or for testing purposes
  90361. */
  90362. var NullEngine = /** @class */ (function (_super) {
  90363. __extends(NullEngine, _super);
  90364. function NullEngine(options) {
  90365. if (options === void 0) { options = new NullEngineOptions(); }
  90366. var _this = _super.call(this, null) || this;
  90367. if (options.deterministicLockstep === undefined) {
  90368. options.deterministicLockstep = false;
  90369. }
  90370. if (options.lockstepMaxSteps === undefined) {
  90371. options.lockstepMaxSteps = 4;
  90372. }
  90373. _this._options = options;
  90374. // Init caps
  90375. // We consider we are on a webgl1 capable device
  90376. _this._caps = new BABYLON.EngineCapabilities();
  90377. _this._caps.maxTexturesImageUnits = 16;
  90378. _this._caps.maxVertexTextureImageUnits = 16;
  90379. _this._caps.maxTextureSize = 512;
  90380. _this._caps.maxCubemapTextureSize = 512;
  90381. _this._caps.maxRenderTextureSize = 512;
  90382. _this._caps.maxVertexAttribs = 16;
  90383. _this._caps.maxVaryingVectors = 16;
  90384. _this._caps.maxFragmentUniformVectors = 16;
  90385. _this._caps.maxVertexUniformVectors = 16;
  90386. // Extensions
  90387. _this._caps.standardDerivatives = false;
  90388. _this._caps.astc = null;
  90389. _this._caps.s3tc = null;
  90390. _this._caps.pvrtc = null;
  90391. _this._caps.etc1 = null;
  90392. _this._caps.etc2 = null;
  90393. _this._caps.textureAnisotropicFilterExtension = null;
  90394. _this._caps.maxAnisotropy = 0;
  90395. _this._caps.uintIndices = false;
  90396. _this._caps.fragmentDepthSupported = false;
  90397. _this._caps.highPrecisionShaderSupported = true;
  90398. _this._caps.colorBufferFloat = false;
  90399. _this._caps.textureFloat = false;
  90400. _this._caps.textureFloatLinearFiltering = false;
  90401. _this._caps.textureFloatRender = false;
  90402. _this._caps.textureHalfFloat = false;
  90403. _this._caps.textureHalfFloatLinearFiltering = false;
  90404. _this._caps.textureHalfFloatRender = false;
  90405. _this._caps.textureLOD = false;
  90406. _this._caps.drawBuffersExtension = false;
  90407. _this._caps.depthTextureExtension = false;
  90408. _this._caps.vertexArrayObject = false;
  90409. _this._caps.instancedArrays = false;
  90410. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90411. // Wrappers
  90412. if (typeof URL === "undefined") {
  90413. URL = {
  90414. createObjectURL: function () { },
  90415. revokeObjectURL: function () { }
  90416. };
  90417. }
  90418. if (typeof Blob === "undefined") {
  90419. Blob = function () { };
  90420. }
  90421. return _this;
  90422. }
  90423. NullEngine.prototype.isDeterministicLockStep = function () {
  90424. return this._options.deterministicLockstep;
  90425. };
  90426. NullEngine.prototype.getLockstepMaxSteps = function () {
  90427. return this._options.lockstepMaxSteps;
  90428. };
  90429. NullEngine.prototype.getHardwareScalingLevel = function () {
  90430. return 1.0;
  90431. };
  90432. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90433. return {
  90434. capacity: 0,
  90435. references: 1,
  90436. is32Bits: false
  90437. };
  90438. };
  90439. NullEngine.prototype.createIndexBuffer = function (indices) {
  90440. return {
  90441. capacity: 0,
  90442. references: 1,
  90443. is32Bits: false
  90444. };
  90445. };
  90446. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90447. if (stencil === void 0) { stencil = false; }
  90448. };
  90449. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90450. if (useScreen === void 0) { useScreen = false; }
  90451. if (!useScreen && this._currentRenderTarget) {
  90452. return this._currentRenderTarget.width;
  90453. }
  90454. return this._options.renderWidth;
  90455. };
  90456. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90457. if (useScreen === void 0) { useScreen = false; }
  90458. if (!useScreen && this._currentRenderTarget) {
  90459. return this._currentRenderTarget.height;
  90460. }
  90461. return this._options.renderHeight;
  90462. };
  90463. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90464. this._cachedViewport = viewport;
  90465. };
  90466. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90467. return {
  90468. transformFeedback: null,
  90469. __SPECTOR_rebuildProgram: null
  90470. };
  90471. };
  90472. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90473. return [];
  90474. };
  90475. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90476. return [];
  90477. };
  90478. NullEngine.prototype.bindSamplers = function (effect) {
  90479. this._currentEffect = null;
  90480. };
  90481. NullEngine.prototype.enableEffect = function (effect) {
  90482. this._currentEffect = effect;
  90483. if (effect.onBind) {
  90484. effect.onBind(effect);
  90485. }
  90486. effect.onBindObservable.notifyObservers(effect);
  90487. };
  90488. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90489. if (zOffset === void 0) { zOffset = 0; }
  90490. if (reverseSide === void 0) { reverseSide = false; }
  90491. };
  90492. NullEngine.prototype.setIntArray = function (uniform, array) {
  90493. };
  90494. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90495. };
  90496. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90497. };
  90498. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90499. };
  90500. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90501. };
  90502. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90503. };
  90504. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90505. };
  90506. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90507. };
  90508. NullEngine.prototype.setArray = function (uniform, array) {
  90509. };
  90510. NullEngine.prototype.setArray2 = function (uniform, array) {
  90511. };
  90512. NullEngine.prototype.setArray3 = function (uniform, array) {
  90513. };
  90514. NullEngine.prototype.setArray4 = function (uniform, array) {
  90515. };
  90516. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90517. };
  90518. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90519. };
  90520. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90521. };
  90522. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90523. };
  90524. NullEngine.prototype.setFloat = function (uniform, value) {
  90525. };
  90526. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90527. };
  90528. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90529. };
  90530. NullEngine.prototype.setBool = function (uniform, bool) {
  90531. };
  90532. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90533. };
  90534. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90535. };
  90536. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90537. };
  90538. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90539. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90540. if (this._alphaMode === mode) {
  90541. return;
  90542. }
  90543. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90544. if (!noDepthWriteChange) {
  90545. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90546. }
  90547. this._alphaMode = mode;
  90548. };
  90549. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90550. };
  90551. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90552. if (this.preventCacheWipeBetweenFrames) {
  90553. return;
  90554. }
  90555. this.resetTextureCache();
  90556. this._currentEffect = null;
  90557. if (bruteForce) {
  90558. this._currentProgram = null;
  90559. this._stencilState.reset();
  90560. this._depthCullingState.reset();
  90561. this._alphaState.reset();
  90562. }
  90563. this._cachedVertexBuffers = null;
  90564. this._cachedIndexBuffer = null;
  90565. this._cachedEffectForVertexBuffers = null;
  90566. };
  90567. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90568. };
  90569. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90570. };
  90571. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90572. };
  90573. NullEngine.prototype._createTexture = function () {
  90574. return {};
  90575. };
  90576. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90578. if (onLoad === void 0) { onLoad = null; }
  90579. if (onError === void 0) { onError = null; }
  90580. if (buffer === void 0) { buffer = null; }
  90581. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90582. var url = String(urlArg);
  90583. texture.url = url;
  90584. texture.generateMipMaps = !noMipmap;
  90585. texture.samplingMode = samplingMode;
  90586. texture.invertY = invertY;
  90587. texture.baseWidth = this._options.textureSize;
  90588. texture.baseHeight = this._options.textureSize;
  90589. texture.width = this._options.textureSize;
  90590. texture.height = this._options.textureSize;
  90591. if (format) {
  90592. texture.format = format;
  90593. }
  90594. texture.isReady = true;
  90595. if (onLoad) {
  90596. onLoad();
  90597. }
  90598. return texture;
  90599. };
  90600. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90601. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90602. if (options !== undefined && typeof options === "object") {
  90603. fullOptions.generateMipMaps = options.generateMipMaps;
  90604. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90605. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90606. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90607. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90608. }
  90609. else {
  90610. fullOptions.generateMipMaps = options;
  90611. fullOptions.generateDepthBuffer = true;
  90612. fullOptions.generateStencilBuffer = false;
  90613. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90614. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90615. }
  90616. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90617. var width = size.width || size;
  90618. var height = size.height || size;
  90619. texture._depthStencilBuffer = {};
  90620. texture._framebuffer = {};
  90621. texture.baseWidth = width;
  90622. texture.baseHeight = height;
  90623. texture.width = width;
  90624. texture.height = height;
  90625. texture.isReady = true;
  90626. texture.samples = 1;
  90627. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90628. texture.samplingMode = fullOptions.samplingMode;
  90629. texture.type = fullOptions.type;
  90630. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90631. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90632. return texture;
  90633. };
  90634. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90635. texture.samplingMode = samplingMode;
  90636. };
  90637. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90638. if (this._currentRenderTarget) {
  90639. this.unBindFramebuffer(this._currentRenderTarget);
  90640. }
  90641. this._currentRenderTarget = texture;
  90642. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90643. if (this._cachedViewport && !forceFullscreenViewport) {
  90644. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90645. }
  90646. };
  90647. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90648. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90649. this._currentRenderTarget = null;
  90650. if (onBeforeUnbind) {
  90651. if (texture._MSAAFramebuffer) {
  90652. this._currentFramebuffer = texture._framebuffer;
  90653. }
  90654. onBeforeUnbind();
  90655. }
  90656. this._currentFramebuffer = null;
  90657. };
  90658. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90659. var vbo = {
  90660. capacity: 1,
  90661. references: 1,
  90662. is32Bits: false
  90663. };
  90664. return vbo;
  90665. };
  90666. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90667. if (offset === void 0) { offset = 0; }
  90668. };
  90669. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90670. };
  90671. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90672. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90673. this._boundTexturesCache[this._activeChannel] = texture;
  90674. }
  90675. };
  90676. NullEngine.prototype._bindTexture = function (channel, texture) {
  90677. if (channel < 0) {
  90678. return;
  90679. }
  90680. this._bindTextureDirectly(0, texture);
  90681. };
  90682. NullEngine.prototype._releaseBuffer = function (buffer) {
  90683. buffer.references--;
  90684. if (buffer.references === 0) {
  90685. return true;
  90686. }
  90687. return false;
  90688. };
  90689. return NullEngine;
  90690. }(BABYLON.Engine));
  90691. BABYLON.NullEngine = NullEngine;
  90692. })(BABYLON || (BABYLON = {}));
  90693. //# sourceMappingURL=babylon.nullEngine.js.map
  90694. "use strict";
  90695. var BABYLON;
  90696. (function (BABYLON) {
  90697. /**
  90698. * This class can be used to get instrumentation data from a Babylon engine
  90699. */
  90700. var EngineInstrumentation = /** @class */ (function () {
  90701. function EngineInstrumentation(engine) {
  90702. this.engine = engine;
  90703. this._captureGPUFrameTime = false;
  90704. this._gpuFrameTime = new BABYLON.PerfCounter();
  90705. this._captureShaderCompilationTime = false;
  90706. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90707. // Observers
  90708. this._onBeginFrameObserver = null;
  90709. this._onEndFrameObserver = null;
  90710. this._onBeforeShaderCompilationObserver = null;
  90711. this._onAfterShaderCompilationObserver = null;
  90712. }
  90713. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90714. // Properties
  90715. /**
  90716. * Gets the perf counter used for GPU frame time
  90717. */
  90718. get: function () {
  90719. return this._gpuFrameTime;
  90720. },
  90721. enumerable: true,
  90722. configurable: true
  90723. });
  90724. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90725. /**
  90726. * Gets the GPU frame time capture status
  90727. */
  90728. get: function () {
  90729. return this._captureGPUFrameTime;
  90730. },
  90731. /**
  90732. * Enable or disable the GPU frame time capture
  90733. */
  90734. set: function (value) {
  90735. var _this = this;
  90736. if (value === this._captureGPUFrameTime) {
  90737. return;
  90738. }
  90739. this._captureGPUFrameTime = value;
  90740. if (value) {
  90741. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90742. if (!_this._gpuFrameTimeToken) {
  90743. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90744. }
  90745. });
  90746. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90747. if (!_this._gpuFrameTimeToken) {
  90748. return;
  90749. }
  90750. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90751. if (time > -1) {
  90752. _this._gpuFrameTimeToken = null;
  90753. _this._gpuFrameTime.fetchNewFrame();
  90754. _this._gpuFrameTime.addCount(time, true);
  90755. }
  90756. });
  90757. }
  90758. else {
  90759. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90760. this._onBeginFrameObserver = null;
  90761. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90762. this._onEndFrameObserver = null;
  90763. }
  90764. },
  90765. enumerable: true,
  90766. configurable: true
  90767. });
  90768. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90769. /**
  90770. * Gets the perf counter used for shader compilation time
  90771. */
  90772. get: function () {
  90773. return this._shaderCompilationTime;
  90774. },
  90775. enumerable: true,
  90776. configurable: true
  90777. });
  90778. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90779. /**
  90780. * Gets the shader compilation time capture status
  90781. */
  90782. get: function () {
  90783. return this._captureShaderCompilationTime;
  90784. },
  90785. /**
  90786. * Enable or disable the shader compilation time capture
  90787. */
  90788. set: function (value) {
  90789. var _this = this;
  90790. if (value === this._captureShaderCompilationTime) {
  90791. return;
  90792. }
  90793. this._captureShaderCompilationTime = value;
  90794. if (value) {
  90795. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90796. _this._shaderCompilationTime.fetchNewFrame();
  90797. _this._shaderCompilationTime.beginMonitoring();
  90798. });
  90799. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90800. _this._shaderCompilationTime.endMonitoring();
  90801. });
  90802. }
  90803. else {
  90804. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90805. this._onBeforeShaderCompilationObserver = null;
  90806. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90807. this._onAfterShaderCompilationObserver = null;
  90808. }
  90809. },
  90810. enumerable: true,
  90811. configurable: true
  90812. });
  90813. EngineInstrumentation.prototype.dispose = function () {
  90814. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90815. this._onBeginFrameObserver = null;
  90816. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90817. this._onEndFrameObserver = null;
  90818. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90819. this._onBeforeShaderCompilationObserver = null;
  90820. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90821. this._onAfterShaderCompilationObserver = null;
  90822. this.engine = null;
  90823. };
  90824. return EngineInstrumentation;
  90825. }());
  90826. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90827. })(BABYLON || (BABYLON = {}));
  90828. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90829. "use strict";
  90830. var BABYLON;
  90831. (function (BABYLON) {
  90832. /**
  90833. * This class can be used to get instrumentation data from a Babylon engine
  90834. */
  90835. var SceneInstrumentation = /** @class */ (function () {
  90836. function SceneInstrumentation(scene) {
  90837. var _this = this;
  90838. this.scene = scene;
  90839. this._captureActiveMeshesEvaluationTime = false;
  90840. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90841. this._captureRenderTargetsRenderTime = false;
  90842. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90843. this._captureFrameTime = false;
  90844. this._frameTime = new BABYLON.PerfCounter();
  90845. this._captureRenderTime = false;
  90846. this._renderTime = new BABYLON.PerfCounter();
  90847. this._captureInterFrameTime = false;
  90848. this._interFrameTime = new BABYLON.PerfCounter();
  90849. this._captureParticlesRenderTime = false;
  90850. this._particlesRenderTime = new BABYLON.PerfCounter();
  90851. this._captureSpritesRenderTime = false;
  90852. this._spritesRenderTime = new BABYLON.PerfCounter();
  90853. this._capturePhysicsTime = false;
  90854. this._physicsTime = new BABYLON.PerfCounter();
  90855. this._captureAnimationsTime = false;
  90856. this._animationsTime = new BABYLON.PerfCounter();
  90857. // Observers
  90858. this._onBeforeActiveMeshesEvaluationObserver = null;
  90859. this._onAfterActiveMeshesEvaluationObserver = null;
  90860. this._onBeforeRenderTargetsRenderObserver = null;
  90861. this._onAfterRenderTargetsRenderObserver = null;
  90862. this._onAfterRenderObserver = null;
  90863. this._onBeforeDrawPhaseObserver = null;
  90864. this._onAfterDrawPhaseObserver = null;
  90865. this._onBeforeAnimationsObserver = null;
  90866. this._onBeforeParticlesRenderingObserver = null;
  90867. this._onAfterParticlesRenderingObserver = null;
  90868. this._onBeforeSpritesRenderingObserver = null;
  90869. this._onAfterSpritesRenderingObserver = null;
  90870. this._onBeforePhysicsObserver = null;
  90871. this._onAfterPhysicsObserver = null;
  90872. this._onAfterAnimationsObserver = null;
  90873. // Before render
  90874. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90875. if (_this._captureActiveMeshesEvaluationTime) {
  90876. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90877. }
  90878. if (_this._captureRenderTargetsRenderTime) {
  90879. _this._renderTargetsRenderTime.fetchNewFrame();
  90880. }
  90881. if (_this._captureFrameTime) {
  90882. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90883. _this._frameTime.beginMonitoring();
  90884. }
  90885. if (_this._captureInterFrameTime) {
  90886. _this._interFrameTime.endMonitoring();
  90887. }
  90888. if (_this._captureParticlesRenderTime) {
  90889. _this._particlesRenderTime.fetchNewFrame();
  90890. }
  90891. if (_this._captureSpritesRenderTime) {
  90892. _this._spritesRenderTime.fetchNewFrame();
  90893. }
  90894. if (_this._captureAnimationsTime) {
  90895. _this._animationsTime.beginMonitoring();
  90896. }
  90897. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90898. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90899. });
  90900. // After render
  90901. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90902. if (_this._captureFrameTime) {
  90903. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90904. _this._frameTime.endMonitoring();
  90905. }
  90906. if (_this._captureRenderTime) {
  90907. _this._renderTime.endMonitoring(false);
  90908. }
  90909. if (_this._captureInterFrameTime) {
  90910. _this._interFrameTime.beginMonitoring();
  90911. }
  90912. });
  90913. }
  90914. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90915. // Properties
  90916. /**
  90917. * Gets the perf counter used for active meshes evaluation time
  90918. */
  90919. get: function () {
  90920. return this._activeMeshesEvaluationTime;
  90921. },
  90922. enumerable: true,
  90923. configurable: true
  90924. });
  90925. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90926. /**
  90927. * Gets the active meshes evaluation time capture status
  90928. */
  90929. get: function () {
  90930. return this._captureActiveMeshesEvaluationTime;
  90931. },
  90932. /**
  90933. * Enable or disable the active meshes evaluation time capture
  90934. */
  90935. set: function (value) {
  90936. var _this = this;
  90937. if (value === this._captureActiveMeshesEvaluationTime) {
  90938. return;
  90939. }
  90940. this._captureActiveMeshesEvaluationTime = value;
  90941. if (value) {
  90942. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90943. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90944. _this._activeMeshesEvaluationTime.beginMonitoring();
  90945. });
  90946. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90947. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90948. _this._activeMeshesEvaluationTime.endMonitoring();
  90949. });
  90950. }
  90951. else {
  90952. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90953. this._onBeforeActiveMeshesEvaluationObserver = null;
  90954. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90955. this._onAfterActiveMeshesEvaluationObserver = null;
  90956. }
  90957. },
  90958. enumerable: true,
  90959. configurable: true
  90960. });
  90961. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90962. /**
  90963. * Gets the perf counter used for render targets render time
  90964. */
  90965. get: function () {
  90966. return this._renderTargetsRenderTime;
  90967. },
  90968. enumerable: true,
  90969. configurable: true
  90970. });
  90971. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90972. /**
  90973. * Gets the render targets render time capture status
  90974. */
  90975. get: function () {
  90976. return this._captureRenderTargetsRenderTime;
  90977. },
  90978. /**
  90979. * Enable or disable the render targets render time capture
  90980. */
  90981. set: function (value) {
  90982. var _this = this;
  90983. if (value === this._captureRenderTargetsRenderTime) {
  90984. return;
  90985. }
  90986. this._captureRenderTargetsRenderTime = value;
  90987. if (value) {
  90988. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  90989. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90990. _this._renderTargetsRenderTime.beginMonitoring();
  90991. });
  90992. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  90993. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90994. _this._renderTargetsRenderTime.endMonitoring(false);
  90995. });
  90996. }
  90997. else {
  90998. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90999. this._onBeforeRenderTargetsRenderObserver = null;
  91000. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  91001. this._onAfterRenderTargetsRenderObserver = null;
  91002. }
  91003. },
  91004. enumerable: true,
  91005. configurable: true
  91006. });
  91007. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  91008. /**
  91009. * Gets the perf counter used for particles render time
  91010. */
  91011. get: function () {
  91012. return this._particlesRenderTime;
  91013. },
  91014. enumerable: true,
  91015. configurable: true
  91016. });
  91017. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  91018. /**
  91019. * Gets the particles render time capture status
  91020. */
  91021. get: function () {
  91022. return this._captureParticlesRenderTime;
  91023. },
  91024. /**
  91025. * Enable or disable the particles render time capture
  91026. */
  91027. set: function (value) {
  91028. var _this = this;
  91029. if (value === this._captureParticlesRenderTime) {
  91030. return;
  91031. }
  91032. this._captureParticlesRenderTime = value;
  91033. if (value) {
  91034. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  91035. BABYLON.Tools.StartPerformanceCounter("Particles");
  91036. _this._particlesRenderTime.beginMonitoring();
  91037. });
  91038. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  91039. BABYLON.Tools.EndPerformanceCounter("Particles");
  91040. _this._particlesRenderTime.endMonitoring(false);
  91041. });
  91042. }
  91043. else {
  91044. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  91045. this._onBeforeParticlesRenderingObserver = null;
  91046. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91047. this._onAfterParticlesRenderingObserver = null;
  91048. }
  91049. },
  91050. enumerable: true,
  91051. configurable: true
  91052. });
  91053. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  91054. /**
  91055. * Gets the perf counter used for sprites render time
  91056. */
  91057. get: function () {
  91058. return this._spritesRenderTime;
  91059. },
  91060. enumerable: true,
  91061. configurable: true
  91062. });
  91063. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  91064. /**
  91065. * Gets the sprites render time capture status
  91066. */
  91067. get: function () {
  91068. return this._captureSpritesRenderTime;
  91069. },
  91070. /**
  91071. * Enable or disable the sprites render time capture
  91072. */
  91073. set: function (value) {
  91074. var _this = this;
  91075. if (value === this._captureSpritesRenderTime) {
  91076. return;
  91077. }
  91078. this._captureSpritesRenderTime = value;
  91079. if (value) {
  91080. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  91081. BABYLON.Tools.StartPerformanceCounter("Sprites");
  91082. _this._spritesRenderTime.beginMonitoring();
  91083. });
  91084. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  91085. BABYLON.Tools.EndPerformanceCounter("Sprites");
  91086. _this._spritesRenderTime.endMonitoring(false);
  91087. });
  91088. }
  91089. else {
  91090. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91091. this._onBeforeSpritesRenderingObserver = null;
  91092. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91093. this._onAfterSpritesRenderingObserver = null;
  91094. }
  91095. },
  91096. enumerable: true,
  91097. configurable: true
  91098. });
  91099. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  91100. /**
  91101. * Gets the perf counter used for physics time
  91102. */
  91103. get: function () {
  91104. return this._physicsTime;
  91105. },
  91106. enumerable: true,
  91107. configurable: true
  91108. });
  91109. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  91110. /**
  91111. * Gets the physics time capture status
  91112. */
  91113. get: function () {
  91114. return this._capturePhysicsTime;
  91115. },
  91116. /**
  91117. * Enable or disable the physics time capture
  91118. */
  91119. set: function (value) {
  91120. var _this = this;
  91121. if (value === this._capturePhysicsTime) {
  91122. return;
  91123. }
  91124. this._capturePhysicsTime = value;
  91125. if (value) {
  91126. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  91127. BABYLON.Tools.StartPerformanceCounter("Physics");
  91128. _this._physicsTime.beginMonitoring();
  91129. });
  91130. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  91131. BABYLON.Tools.EndPerformanceCounter("Physics");
  91132. _this._physicsTime.endMonitoring();
  91133. });
  91134. }
  91135. else {
  91136. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91137. this._onBeforePhysicsObserver = null;
  91138. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91139. this._onAfterPhysicsObserver = null;
  91140. }
  91141. },
  91142. enumerable: true,
  91143. configurable: true
  91144. });
  91145. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  91146. /**
  91147. * Gets the perf counter used for animations time
  91148. */
  91149. get: function () {
  91150. return this._animationsTime;
  91151. },
  91152. enumerable: true,
  91153. configurable: true
  91154. });
  91155. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  91156. /**
  91157. * Gets the animations time capture status
  91158. */
  91159. get: function () {
  91160. return this._captureAnimationsTime;
  91161. },
  91162. /**
  91163. * Enable or disable the animations time capture
  91164. */
  91165. set: function (value) {
  91166. var _this = this;
  91167. if (value === this._captureAnimationsTime) {
  91168. return;
  91169. }
  91170. this._captureAnimationsTime = value;
  91171. if (value) {
  91172. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  91173. _this._animationsTime.endMonitoring();
  91174. });
  91175. }
  91176. else {
  91177. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91178. this._onAfterAnimationsObserver = null;
  91179. }
  91180. },
  91181. enumerable: true,
  91182. configurable: true
  91183. });
  91184. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  91185. /**
  91186. * Gets the perf counter used for frame time capture
  91187. */
  91188. get: function () {
  91189. return this._frameTime;
  91190. },
  91191. enumerable: true,
  91192. configurable: true
  91193. });
  91194. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  91195. /**
  91196. * Gets the frame time capture status
  91197. */
  91198. get: function () {
  91199. return this._captureFrameTime;
  91200. },
  91201. /**
  91202. * Enable or disable the frame time capture
  91203. */
  91204. set: function (value) {
  91205. this._captureFrameTime = value;
  91206. },
  91207. enumerable: true,
  91208. configurable: true
  91209. });
  91210. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  91211. /**
  91212. * Gets the perf counter used for inter-frames time capture
  91213. */
  91214. get: function () {
  91215. return this._interFrameTime;
  91216. },
  91217. enumerable: true,
  91218. configurable: true
  91219. });
  91220. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  91221. /**
  91222. * Gets the inter-frames time capture status
  91223. */
  91224. get: function () {
  91225. return this._captureInterFrameTime;
  91226. },
  91227. /**
  91228. * Enable or disable the inter-frames time capture
  91229. */
  91230. set: function (value) {
  91231. this._captureInterFrameTime = value;
  91232. },
  91233. enumerable: true,
  91234. configurable: true
  91235. });
  91236. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  91237. /**
  91238. * Gets the perf counter used for render time capture
  91239. */
  91240. get: function () {
  91241. return this._renderTime;
  91242. },
  91243. enumerable: true,
  91244. configurable: true
  91245. });
  91246. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  91247. /**
  91248. * Gets the render time capture status
  91249. */
  91250. get: function () {
  91251. return this._captureRenderTime;
  91252. },
  91253. /**
  91254. * Enable or disable the render time capture
  91255. */
  91256. set: function (value) {
  91257. var _this = this;
  91258. if (value === this._captureRenderTime) {
  91259. return;
  91260. }
  91261. this._captureRenderTime = value;
  91262. if (value) {
  91263. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  91264. _this._renderTime.beginMonitoring();
  91265. BABYLON.Tools.StartPerformanceCounter("Main render");
  91266. });
  91267. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  91268. _this._renderTime.endMonitoring(false);
  91269. BABYLON.Tools.EndPerformanceCounter("Main render");
  91270. });
  91271. }
  91272. else {
  91273. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91274. this._onBeforeDrawPhaseObserver = null;
  91275. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91276. this._onAfterDrawPhaseObserver = null;
  91277. }
  91278. },
  91279. enumerable: true,
  91280. configurable: true
  91281. });
  91282. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  91283. /**
  91284. * Gets the perf counter used for draw calls
  91285. */
  91286. get: function () {
  91287. return this.scene.getEngine()._drawCalls;
  91288. },
  91289. enumerable: true,
  91290. configurable: true
  91291. });
  91292. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  91293. /**
  91294. * Gets the perf counter used for texture collisions
  91295. */
  91296. get: function () {
  91297. return this.scene.getEngine()._textureCollisions;
  91298. },
  91299. enumerable: true,
  91300. configurable: true
  91301. });
  91302. SceneInstrumentation.prototype.dispose = function () {
  91303. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91304. this._onAfterRenderObserver = null;
  91305. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  91306. this._onBeforeActiveMeshesEvaluationObserver = null;
  91307. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  91308. this._onAfterActiveMeshesEvaluationObserver = null;
  91309. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  91310. this._onBeforeRenderTargetsRenderObserver = null;
  91311. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  91312. this._onAfterRenderTargetsRenderObserver = null;
  91313. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  91314. this._onBeforeAnimationsObserver = null;
  91315. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  91316. this._onBeforeParticlesRenderingObserver = null;
  91317. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91318. this._onAfterParticlesRenderingObserver = null;
  91319. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91320. this._onBeforeSpritesRenderingObserver = null;
  91321. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91322. this._onAfterSpritesRenderingObserver = null;
  91323. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91324. this._onBeforeDrawPhaseObserver = null;
  91325. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91326. this._onAfterDrawPhaseObserver = null;
  91327. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91328. this._onBeforePhysicsObserver = null;
  91329. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91330. this._onAfterPhysicsObserver = null;
  91331. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91332. this._onAfterAnimationsObserver = null;
  91333. this.scene = null;
  91334. };
  91335. return SceneInstrumentation;
  91336. }());
  91337. BABYLON.SceneInstrumentation = SceneInstrumentation;
  91338. })(BABYLON || (BABYLON = {}));
  91339. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  91340. "use strict";
  91341. var BABYLON;
  91342. (function (BABYLON) {
  91343. var _TimeToken = /** @class */ (function () {
  91344. function _TimeToken() {
  91345. this._timeElapsedQueryEnded = false;
  91346. }
  91347. return _TimeToken;
  91348. }());
  91349. BABYLON._TimeToken = _TimeToken;
  91350. })(BABYLON || (BABYLON = {}));
  91351. //# sourceMappingURL=babylon.timeToken.js.map
  91352. "use strict";
  91353. var BABYLON;
  91354. (function (BABYLON) {
  91355. /**
  91356. * Background material defines definition.
  91357. * @ignore Mainly internal Use
  91358. */
  91359. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91360. __extends(BackgroundMaterialDefines, _super);
  91361. /**
  91362. * Constructor of the defines.
  91363. */
  91364. function BackgroundMaterialDefines() {
  91365. var _this = _super.call(this) || this;
  91366. /**
  91367. * True if the diffuse texture is in use.
  91368. */
  91369. _this.DIFFUSE = false;
  91370. /**
  91371. * The direct UV channel to use.
  91372. */
  91373. _this.DIFFUSEDIRECTUV = 0;
  91374. /**
  91375. * True if the diffuse texture is in gamma space.
  91376. */
  91377. _this.GAMMADIFFUSE = false;
  91378. /**
  91379. * True if the diffuse texture has opacity in the alpha channel.
  91380. */
  91381. _this.DIFFUSEHASALPHA = false;
  91382. /**
  91383. * True if you want the material to fade to transparent at grazing angle.
  91384. */
  91385. _this.OPACITYFRESNEL = false;
  91386. /**
  91387. * True if an extra blur needs to be added in the reflection.
  91388. */
  91389. _this.REFLECTIONBLUR = false;
  91390. /**
  91391. * True if you want the material to fade to reflection at grazing angle.
  91392. */
  91393. _this.REFLECTIONFRESNEL = false;
  91394. /**
  91395. * True if you want the material to falloff as far as you move away from the scene center.
  91396. */
  91397. _this.REFLECTIONFALLOFF = false;
  91398. /**
  91399. * False if the current Webgl implementation does not support the texture lod extension.
  91400. */
  91401. _this.TEXTURELODSUPPORT = false;
  91402. /**
  91403. * True to ensure the data are premultiplied.
  91404. */
  91405. _this.PREMULTIPLYALPHA = false;
  91406. /**
  91407. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91408. */
  91409. _this.USERGBCOLOR = false;
  91410. /**
  91411. * True to add noise in order to reduce the banding effect.
  91412. */
  91413. _this.NOISE = false;
  91414. /**
  91415. * is the reflection texture in BGR color scheme?
  91416. * Mainly used to solve a bug in ios10 video tag
  91417. */
  91418. _this.REFLECTIONBGR = false;
  91419. _this.IMAGEPROCESSING = false;
  91420. _this.VIGNETTE = false;
  91421. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91422. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91423. _this.TONEMAPPING = false;
  91424. _this.CONTRAST = false;
  91425. _this.COLORCURVES = false;
  91426. _this.COLORGRADING = false;
  91427. _this.COLORGRADING3D = false;
  91428. _this.SAMPLER3DGREENDEPTH = false;
  91429. _this.SAMPLER3DBGRMAP = false;
  91430. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91431. _this.EXPOSURE = false;
  91432. // Reflection.
  91433. _this.REFLECTION = false;
  91434. _this.REFLECTIONMAP_3D = false;
  91435. _this.REFLECTIONMAP_SPHERICAL = false;
  91436. _this.REFLECTIONMAP_PLANAR = false;
  91437. _this.REFLECTIONMAP_CUBIC = false;
  91438. _this.REFLECTIONMAP_PROJECTION = false;
  91439. _this.REFLECTIONMAP_SKYBOX = false;
  91440. _this.REFLECTIONMAP_EXPLICIT = false;
  91441. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91442. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91443. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91444. _this.INVERTCUBICMAP = false;
  91445. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91446. _this.LODINREFLECTIONALPHA = false;
  91447. _this.GAMMAREFLECTION = false;
  91448. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91449. // Default BJS.
  91450. _this.MAINUV1 = false;
  91451. _this.MAINUV2 = false;
  91452. _this.UV1 = false;
  91453. _this.UV2 = false;
  91454. _this.CLIPPLANE = false;
  91455. _this.POINTSIZE = false;
  91456. _this.FOG = false;
  91457. _this.NORMAL = false;
  91458. _this.NUM_BONE_INFLUENCERS = 0;
  91459. _this.BonesPerMesh = 0;
  91460. _this.INSTANCES = false;
  91461. _this.SHADOWFLOAT = false;
  91462. _this.rebuild();
  91463. return _this;
  91464. }
  91465. return BackgroundMaterialDefines;
  91466. }(BABYLON.MaterialDefines));
  91467. /**
  91468. * Background material used to create an efficient environement around your scene.
  91469. */
  91470. var BackgroundMaterial = /** @class */ (function (_super) {
  91471. __extends(BackgroundMaterial, _super);
  91472. /**
  91473. * Instantiates a Background Material in the given scene
  91474. * @param name The friendly name of the material
  91475. * @param scene The scene to add the material to
  91476. */
  91477. function BackgroundMaterial(name, scene) {
  91478. var _this = _super.call(this, name, scene) || this;
  91479. /**
  91480. * Key light Color (multiply against the R channel of the environement texture)
  91481. */
  91482. _this.primaryColor = BABYLON.Color3.White();
  91483. /**
  91484. * Key light Level (allowing HDR output of the background)
  91485. */
  91486. _this.primaryLevel = 1;
  91487. /**
  91488. * Secondary light Color (multiply against the G channel of the environement texture)
  91489. */
  91490. _this.secondaryColor = BABYLON.Color3.Gray();
  91491. /**
  91492. * Secondary light Level (allowing HDR output of the background)
  91493. */
  91494. _this.secondaryLevel = 1;
  91495. /**
  91496. * Tertiary light Color (multiply against the B channel of the environement texture)
  91497. */
  91498. _this.tertiaryColor = BABYLON.Color3.Black();
  91499. /**
  91500. * Tertiary light Level (allowing HDR output of the background)
  91501. */
  91502. _this.tertiaryLevel = 1;
  91503. /**
  91504. * Reflection Texture used in the material.
  91505. * Should be author in a specific way for the best result (refer to the documentation).
  91506. */
  91507. _this.reflectionTexture = null;
  91508. /**
  91509. * Reflection Texture level of blur.
  91510. *
  91511. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91512. * texture twice.
  91513. */
  91514. _this.reflectionBlur = 0;
  91515. /**
  91516. * Diffuse Texture used in the material.
  91517. * Should be author in a specific way for the best result (refer to the documentation).
  91518. */
  91519. _this.diffuseTexture = null;
  91520. _this._shadowLights = null;
  91521. /**
  91522. * Specify the list of lights casting shadow on the material.
  91523. * All scene shadow lights will be included if null.
  91524. */
  91525. _this.shadowLights = null;
  91526. /**
  91527. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91528. * soft lighting on the background.
  91529. */
  91530. _this.shadowBlurScale = 1;
  91531. /**
  91532. * Helps adjusting the shadow to a softer level if required.
  91533. * 0 means black shadows and 1 means no shadows.
  91534. */
  91535. _this.shadowLevel = 0;
  91536. /**
  91537. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91538. * It is usually zero but might be interesting to modify according to your setup.
  91539. */
  91540. _this.sceneCenter = BABYLON.Vector3.Zero();
  91541. /**
  91542. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91543. * This helps ensuring a nice transition when the camera goes under the ground.
  91544. */
  91545. _this.opacityFresnel = true;
  91546. /**
  91547. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91548. * This helps adding a mirror texture on the ground.
  91549. */
  91550. _this.reflectionFresnel = false;
  91551. /**
  91552. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91553. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91554. */
  91555. _this.reflectionFalloffDistance = 0.0;
  91556. /**
  91557. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91558. */
  91559. _this.reflectionAmount = 1.0;
  91560. /**
  91561. * This specifies the weight of the reflection at grazing angle.
  91562. */
  91563. _this.reflectionReflectance0 = 0.05;
  91564. /**
  91565. * This specifies the weight of the reflection at a perpendicular point of view.
  91566. */
  91567. _this.reflectionReflectance90 = 0.5;
  91568. /**
  91569. * Helps to directly use the maps channels instead of their level.
  91570. */
  91571. _this.useRGBColor = true;
  91572. /**
  91573. * This helps reducing the banding effect that could occur on the background.
  91574. */
  91575. _this.enableNoise = false;
  91576. _this._fovMultiplier = 1.0;
  91577. /**
  91578. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91579. */
  91580. _this.useEquirectangularFOV = false;
  91581. _this._maxSimultaneousLights = 4;
  91582. /**
  91583. * Number of Simultaneous lights allowed on the material.
  91584. */
  91585. _this.maxSimultaneousLights = 4;
  91586. /**
  91587. * Keep track of the image processing observer to allow dispose and replace.
  91588. */
  91589. _this._imageProcessingObserver = null;
  91590. /**
  91591. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91592. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91593. */
  91594. _this.switchToBGR = false;
  91595. // Temp values kept as cache in the material.
  91596. _this._renderTargets = new BABYLON.SmartArray(16);
  91597. _this._reflectionControls = BABYLON.Vector4.Zero();
  91598. // Setup the default processing configuration to the scene.
  91599. _this._attachImageProcessingConfiguration(null);
  91600. _this.getRenderTargetTextures = function () {
  91601. _this._renderTargets.reset();
  91602. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91603. _this._renderTargets.push(_this._diffuseTexture);
  91604. }
  91605. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91606. _this._renderTargets.push(_this._reflectionTexture);
  91607. }
  91608. return _this._renderTargets;
  91609. };
  91610. return _this;
  91611. }
  91612. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91613. /**
  91614. * Sets the reflection reflectance fresnel values according to the default standard
  91615. * empirically know to work well :-)
  91616. */
  91617. set: function (value) {
  91618. var reflectionWeight = value;
  91619. if (reflectionWeight < 0.5) {
  91620. reflectionWeight = reflectionWeight * 2.0;
  91621. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91622. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91623. }
  91624. else {
  91625. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91626. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91627. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91628. }
  91629. },
  91630. enumerable: true,
  91631. configurable: true
  91632. });
  91633. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91634. /**
  91635. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91636. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91637. * Recommended to be keep at 1.0 except for special cases.
  91638. */
  91639. get: function () {
  91640. return this._fovMultiplier;
  91641. },
  91642. set: function (value) {
  91643. if (isNaN(value)) {
  91644. value = 1.0;
  91645. }
  91646. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91647. },
  91648. enumerable: true,
  91649. configurable: true
  91650. });
  91651. /**
  91652. * Attaches a new image processing configuration to the PBR Material.
  91653. * @param configuration (if null the scene configuration will be use)
  91654. */
  91655. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91656. var _this = this;
  91657. if (configuration === this._imageProcessingConfiguration) {
  91658. return;
  91659. }
  91660. // Detaches observer.
  91661. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91662. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91663. }
  91664. // Pick the scene configuration if needed.
  91665. if (!configuration) {
  91666. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91667. }
  91668. else {
  91669. this._imageProcessingConfiguration = configuration;
  91670. }
  91671. // Attaches observer.
  91672. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91673. _this._markAllSubMeshesAsImageProcessingDirty();
  91674. });
  91675. };
  91676. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91677. /**
  91678. * Gets the image processing configuration used either in this material.
  91679. */
  91680. get: function () {
  91681. return this._imageProcessingConfiguration;
  91682. },
  91683. /**
  91684. * Sets the Default image processing configuration used either in the this material.
  91685. *
  91686. * If sets to null, the scene one is in use.
  91687. */
  91688. set: function (value) {
  91689. this._attachImageProcessingConfiguration(value);
  91690. // Ensure the effect will be rebuilt.
  91691. this._markAllSubMeshesAsTexturesDirty();
  91692. },
  91693. enumerable: true,
  91694. configurable: true
  91695. });
  91696. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91697. /**
  91698. * Gets wether the color curves effect is enabled.
  91699. */
  91700. get: function () {
  91701. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91702. },
  91703. /**
  91704. * Sets wether the color curves effect is enabled.
  91705. */
  91706. set: function (value) {
  91707. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91708. },
  91709. enumerable: true,
  91710. configurable: true
  91711. });
  91712. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91713. /**
  91714. * Gets wether the color grading effect is enabled.
  91715. */
  91716. get: function () {
  91717. return this.imageProcessingConfiguration.colorGradingEnabled;
  91718. },
  91719. /**
  91720. * Gets wether the color grading effect is enabled.
  91721. */
  91722. set: function (value) {
  91723. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91724. },
  91725. enumerable: true,
  91726. configurable: true
  91727. });
  91728. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91729. /**
  91730. * Gets wether tonemapping is enabled or not.
  91731. */
  91732. get: function () {
  91733. return this._imageProcessingConfiguration.toneMappingEnabled;
  91734. },
  91735. /**
  91736. * Sets wether tonemapping is enabled or not
  91737. */
  91738. set: function (value) {
  91739. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91740. },
  91741. enumerable: true,
  91742. configurable: true
  91743. });
  91744. ;
  91745. ;
  91746. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91747. /**
  91748. * The camera exposure used on this material.
  91749. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91750. * This corresponds to a photographic exposure.
  91751. */
  91752. get: function () {
  91753. return this._imageProcessingConfiguration.exposure;
  91754. },
  91755. /**
  91756. * The camera exposure used on this material.
  91757. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91758. * This corresponds to a photographic exposure.
  91759. */
  91760. set: function (value) {
  91761. this._imageProcessingConfiguration.exposure = value;
  91762. },
  91763. enumerable: true,
  91764. configurable: true
  91765. });
  91766. ;
  91767. ;
  91768. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91769. /**
  91770. * Gets The camera contrast used on this material.
  91771. */
  91772. get: function () {
  91773. return this._imageProcessingConfiguration.contrast;
  91774. },
  91775. /**
  91776. * Sets The camera contrast used on this material.
  91777. */
  91778. set: function (value) {
  91779. this._imageProcessingConfiguration.contrast = value;
  91780. },
  91781. enumerable: true,
  91782. configurable: true
  91783. });
  91784. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91785. /**
  91786. * Gets the Color Grading 2D Lookup Texture.
  91787. */
  91788. get: function () {
  91789. return this._imageProcessingConfiguration.colorGradingTexture;
  91790. },
  91791. /**
  91792. * Sets the Color Grading 2D Lookup Texture.
  91793. */
  91794. set: function (value) {
  91795. this.imageProcessingConfiguration.colorGradingTexture = value;
  91796. },
  91797. enumerable: true,
  91798. configurable: true
  91799. });
  91800. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91801. /**
  91802. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91803. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91804. * 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;
  91805. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91806. */
  91807. get: function () {
  91808. return this.imageProcessingConfiguration.colorCurves;
  91809. },
  91810. /**
  91811. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91812. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91813. * 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;
  91814. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91815. */
  91816. set: function (value) {
  91817. this.imageProcessingConfiguration.colorCurves = value;
  91818. },
  91819. enumerable: true,
  91820. configurable: true
  91821. });
  91822. /**
  91823. * The entire material has been created in order to prevent overdraw.
  91824. * @returns false
  91825. */
  91826. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91827. return true;
  91828. };
  91829. /**
  91830. * The entire material has been created in order to prevent overdraw.
  91831. * @returns true if blending is enable
  91832. */
  91833. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91834. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91835. };
  91836. /**
  91837. * Checks wether the material is ready to be rendered for a given mesh.
  91838. * @param mesh The mesh to render
  91839. * @param subMesh The submesh to check against
  91840. * @param useInstances Specify wether or not the material is used with instances
  91841. * @returns true if all the dependencies are ready (Textures, Effects...)
  91842. */
  91843. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91844. var _this = this;
  91845. if (useInstances === void 0) { useInstances = false; }
  91846. if (subMesh.effect && this.isFrozen) {
  91847. if (this._wasPreviouslyReady) {
  91848. return true;
  91849. }
  91850. }
  91851. if (!subMesh._materialDefines) {
  91852. subMesh._materialDefines = new BackgroundMaterialDefines();
  91853. }
  91854. var scene = this.getScene();
  91855. var defines = subMesh._materialDefines;
  91856. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91857. if (defines._renderId === scene.getRenderId()) {
  91858. return true;
  91859. }
  91860. }
  91861. var engine = scene.getEngine();
  91862. // Lights
  91863. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91864. defines._needNormals = true;
  91865. // Textures
  91866. if (defines._areTexturesDirty) {
  91867. defines._needUVs = false;
  91868. if (scene.texturesEnabled) {
  91869. if (scene.getEngine().getCaps().textureLOD) {
  91870. defines.TEXTURELODSUPPORT = true;
  91871. }
  91872. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91873. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91874. return false;
  91875. }
  91876. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91877. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91878. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91879. defines.OPACITYFRESNEL = this._opacityFresnel;
  91880. }
  91881. else {
  91882. defines.DIFFUSE = false;
  91883. defines.DIFFUSEHASALPHA = false;
  91884. defines.GAMMADIFFUSE = false;
  91885. defines.OPACITYFRESNEL = false;
  91886. }
  91887. var reflectionTexture = this._reflectionTexture;
  91888. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91889. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91890. return false;
  91891. }
  91892. defines.REFLECTION = true;
  91893. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91894. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91895. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91896. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91897. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91898. defines.REFLECTIONBGR = this.switchToBGR;
  91899. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91900. defines.INVERTCUBICMAP = true;
  91901. }
  91902. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91903. switch (reflectionTexture.coordinatesMode) {
  91904. case BABYLON.Texture.CUBIC_MODE:
  91905. case BABYLON.Texture.INVCUBIC_MODE:
  91906. defines.REFLECTIONMAP_CUBIC = true;
  91907. break;
  91908. case BABYLON.Texture.EXPLICIT_MODE:
  91909. defines.REFLECTIONMAP_EXPLICIT = true;
  91910. break;
  91911. case BABYLON.Texture.PLANAR_MODE:
  91912. defines.REFLECTIONMAP_PLANAR = true;
  91913. break;
  91914. case BABYLON.Texture.PROJECTION_MODE:
  91915. defines.REFLECTIONMAP_PROJECTION = true;
  91916. break;
  91917. case BABYLON.Texture.SKYBOX_MODE:
  91918. defines.REFLECTIONMAP_SKYBOX = true;
  91919. break;
  91920. case BABYLON.Texture.SPHERICAL_MODE:
  91921. defines.REFLECTIONMAP_SPHERICAL = true;
  91922. break;
  91923. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91924. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91925. break;
  91926. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91927. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91928. break;
  91929. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91930. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91931. break;
  91932. }
  91933. if (this.reflectionFresnel) {
  91934. defines.REFLECTIONFRESNEL = true;
  91935. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91936. this._reflectionControls.x = this.reflectionAmount;
  91937. this._reflectionControls.y = this.reflectionReflectance0;
  91938. this._reflectionControls.z = this.reflectionReflectance90;
  91939. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91940. }
  91941. else {
  91942. defines.REFLECTIONFRESNEL = false;
  91943. defines.REFLECTIONFALLOFF = false;
  91944. }
  91945. }
  91946. else {
  91947. defines.REFLECTION = false;
  91948. defines.REFLECTIONFALLOFF = false;
  91949. defines.REFLECTIONBLUR = false;
  91950. defines.REFLECTIONMAP_3D = false;
  91951. defines.REFLECTIONMAP_SPHERICAL = false;
  91952. defines.REFLECTIONMAP_PLANAR = false;
  91953. defines.REFLECTIONMAP_CUBIC = false;
  91954. defines.REFLECTIONMAP_PROJECTION = false;
  91955. defines.REFLECTIONMAP_SKYBOX = false;
  91956. defines.REFLECTIONMAP_EXPLICIT = false;
  91957. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91958. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91959. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91960. defines.INVERTCUBICMAP = false;
  91961. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91962. defines.LODINREFLECTIONALPHA = false;
  91963. defines.GAMMAREFLECTION = false;
  91964. }
  91965. }
  91966. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91967. defines.USERGBCOLOR = this._useRGBColor;
  91968. defines.NOISE = this._enableNoise;
  91969. }
  91970. if (defines._areImageProcessingDirty) {
  91971. if (!this._imageProcessingConfiguration.isReady()) {
  91972. return false;
  91973. }
  91974. this._imageProcessingConfiguration.prepareDefines(defines);
  91975. }
  91976. // Misc.
  91977. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91978. // Values that need to be evaluated on every frame
  91979. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91980. // Attribs
  91981. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91982. if (mesh) {
  91983. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91984. mesh.createNormals(true);
  91985. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91986. }
  91987. }
  91988. }
  91989. // Get correct effect
  91990. if (defines.isDirty) {
  91991. defines.markAsProcessed();
  91992. scene.resetCachedMaterial();
  91993. // Fallbacks
  91994. var fallbacks = new BABYLON.EffectFallbacks();
  91995. if (defines.FOG) {
  91996. fallbacks.addFallback(0, "FOG");
  91997. }
  91998. if (defines.POINTSIZE) {
  91999. fallbacks.addFallback(1, "POINTSIZE");
  92000. }
  92001. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  92002. if (defines.NUM_BONE_INFLUENCERS > 0) {
  92003. fallbacks.addCPUSkinningFallback(0, mesh);
  92004. }
  92005. //Attributes
  92006. var attribs = [BABYLON.VertexBuffer.PositionKind];
  92007. if (defines.NORMAL) {
  92008. attribs.push(BABYLON.VertexBuffer.NormalKind);
  92009. }
  92010. if (defines.UV1) {
  92011. attribs.push(BABYLON.VertexBuffer.UVKind);
  92012. }
  92013. if (defines.UV2) {
  92014. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  92015. }
  92016. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  92017. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  92018. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  92019. "vFogInfos", "vFogColor", "pointSize",
  92020. "vClipPlane", "mBones",
  92021. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  92022. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  92023. "shadowLevel", "alpha",
  92024. "vBackgroundCenter", "vReflectionControl",
  92025. "vDiffuseInfos", "diffuseMatrix",
  92026. ];
  92027. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  92028. var uniformBuffers = ["Material", "Scene"];
  92029. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  92030. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  92031. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  92032. uniformsNames: uniforms,
  92033. uniformBuffersNames: uniformBuffers,
  92034. samplers: samplers,
  92035. defines: defines,
  92036. maxSimultaneousLights: this._maxSimultaneousLights
  92037. });
  92038. var onCompiled = function (effect) {
  92039. if (_this.onCompiled) {
  92040. _this.onCompiled(effect);
  92041. }
  92042. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  92043. };
  92044. var join = defines.toString();
  92045. subMesh.setEffect(scene.getEngine().createEffect("background", {
  92046. attributes: attribs,
  92047. uniformsNames: uniforms,
  92048. uniformBuffersNames: uniformBuffers,
  92049. samplers: samplers,
  92050. defines: join,
  92051. fallbacks: fallbacks,
  92052. onCompiled: onCompiled,
  92053. onError: this.onError,
  92054. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  92055. }, engine), defines);
  92056. this.buildUniformLayout();
  92057. }
  92058. if (!subMesh.effect || !subMesh.effect.isReady()) {
  92059. return false;
  92060. }
  92061. defines._renderId = scene.getRenderId();
  92062. this._wasPreviouslyReady = true;
  92063. return true;
  92064. };
  92065. /**
  92066. * Build the uniform buffer used in the material.
  92067. */
  92068. BackgroundMaterial.prototype.buildUniformLayout = function () {
  92069. // Order is important !
  92070. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  92071. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  92072. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  92073. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  92074. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  92075. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  92076. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  92077. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  92078. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  92079. this._uniformBuffer.addUniform("pointSize", 1);
  92080. this._uniformBuffer.addUniform("shadowLevel", 1);
  92081. this._uniformBuffer.addUniform("alpha", 1);
  92082. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  92083. this._uniformBuffer.addUniform("vReflectionControl", 4);
  92084. this._uniformBuffer.create();
  92085. };
  92086. /**
  92087. * Unbind the material.
  92088. */
  92089. BackgroundMaterial.prototype.unbind = function () {
  92090. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  92091. this._uniformBuffer.setTexture("diffuseSampler", null);
  92092. }
  92093. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  92094. this._uniformBuffer.setTexture("reflectionSampler", null);
  92095. }
  92096. _super.prototype.unbind.call(this);
  92097. };
  92098. /**
  92099. * Bind only the world matrix to the material.
  92100. * @param world The world matrix to bind.
  92101. */
  92102. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  92103. this._activeEffect.setMatrix("world", world);
  92104. };
  92105. /**
  92106. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  92107. * @param world The world matrix to bind.
  92108. * @param subMesh The submesh to bind for.
  92109. */
  92110. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  92111. var scene = this.getScene();
  92112. var defines = subMesh._materialDefines;
  92113. if (!defines) {
  92114. return;
  92115. }
  92116. var effect = subMesh.effect;
  92117. if (!effect) {
  92118. return;
  92119. }
  92120. this._activeEffect = effect;
  92121. // Matrices
  92122. this.bindOnlyWorldMatrix(world);
  92123. // Bones
  92124. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  92125. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  92126. if (mustRebind) {
  92127. this._uniformBuffer.bindToEffect(effect, "Material");
  92128. this.bindViewProjection(effect);
  92129. var reflectionTexture = this._reflectionTexture;
  92130. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  92131. // Texture uniforms
  92132. if (scene.texturesEnabled) {
  92133. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  92134. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  92135. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  92136. }
  92137. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  92138. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  92139. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  92140. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  92141. }
  92142. }
  92143. if (this.shadowLevel > 0) {
  92144. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  92145. }
  92146. this._uniformBuffer.updateFloat("alpha", this.alpha);
  92147. // Point size
  92148. if (this.pointsCloud) {
  92149. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  92150. }
  92151. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  92152. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  92153. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  92154. }
  92155. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  92156. // Textures
  92157. if (scene.texturesEnabled) {
  92158. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  92159. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  92160. }
  92161. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  92162. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  92163. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  92164. }
  92165. else if (!defines.REFLECTIONBLUR) {
  92166. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  92167. }
  92168. else {
  92169. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  92170. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  92171. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  92172. }
  92173. if (defines.REFLECTIONFRESNEL) {
  92174. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  92175. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  92176. }
  92177. }
  92178. }
  92179. // Clip plane
  92180. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  92181. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  92182. }
  92183. if (mustRebind || !this.isFrozen) {
  92184. if (scene.lightsEnabled) {
  92185. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  92186. }
  92187. // View
  92188. this.bindView(effect);
  92189. // Fog
  92190. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  92191. // image processing
  92192. this._imageProcessingConfiguration.bind(this._activeEffect);
  92193. }
  92194. this._uniformBuffer.update();
  92195. this._afterBind(mesh);
  92196. };
  92197. /**
  92198. * Dispose the material.
  92199. * @param forceDisposeEffect Force disposal of the associated effect.
  92200. * @param forceDisposeTextures Force disposal of the associated textures.
  92201. */
  92202. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  92203. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  92204. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  92205. if (forceDisposeTextures) {
  92206. if (this.diffuseTexture) {
  92207. this.diffuseTexture.dispose();
  92208. }
  92209. if (this.reflectionTexture) {
  92210. this.reflectionTexture.dispose();
  92211. }
  92212. }
  92213. this._renderTargets.dispose();
  92214. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  92215. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  92216. }
  92217. _super.prototype.dispose.call(this, forceDisposeEffect);
  92218. };
  92219. /**
  92220. * Clones the material.
  92221. * @param name The cloned name.
  92222. * @returns The cloned material.
  92223. */
  92224. BackgroundMaterial.prototype.clone = function (name) {
  92225. var _this = this;
  92226. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  92227. };
  92228. /**
  92229. * Serializes the current material to its JSON representation.
  92230. * @returns The JSON representation.
  92231. */
  92232. BackgroundMaterial.prototype.serialize = function () {
  92233. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92234. serializationObject.customType = "BABYLON.BackgroundMaterial";
  92235. return serializationObject;
  92236. };
  92237. /**
  92238. * Gets the class name of the material
  92239. * @returns "BackgroundMaterial"
  92240. */
  92241. BackgroundMaterial.prototype.getClassName = function () {
  92242. return "BackgroundMaterial";
  92243. };
  92244. /**
  92245. * Parse a JSON input to create back a background material.
  92246. * @param source The JSON data to parse
  92247. * @param scene The scene to create the parsed material in
  92248. * @param rootUrl The root url of the assets the material depends upon
  92249. * @returns the instantiated BackgroundMaterial.
  92250. */
  92251. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  92252. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  92253. };
  92254. /**
  92255. * Standard reflectance value at parallel view angle.
  92256. */
  92257. BackgroundMaterial.StandardReflectance0 = 0.05;
  92258. /**
  92259. * Standard reflectance value at grazing angle.
  92260. */
  92261. BackgroundMaterial.StandardReflectance90 = 0.5;
  92262. __decorate([
  92263. BABYLON.serializeAsColor3()
  92264. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  92265. __decorate([
  92266. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92267. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  92268. __decorate([
  92269. BABYLON.serialize()
  92270. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  92271. __decorate([
  92272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92273. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  92274. __decorate([
  92275. BABYLON.serializeAsColor3()
  92276. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  92277. __decorate([
  92278. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92279. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  92280. __decorate([
  92281. BABYLON.serialize()
  92282. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  92283. __decorate([
  92284. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92285. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  92286. __decorate([
  92287. BABYLON.serializeAsColor3()
  92288. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  92289. __decorate([
  92290. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92291. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  92292. __decorate([
  92293. BABYLON.serialize()
  92294. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  92295. __decorate([
  92296. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92297. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  92298. __decorate([
  92299. BABYLON.serializeAsTexture()
  92300. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  92301. __decorate([
  92302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92303. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  92304. __decorate([
  92305. BABYLON.serialize()
  92306. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  92307. __decorate([
  92308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92309. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  92310. __decorate([
  92311. BABYLON.serializeAsTexture()
  92312. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  92313. __decorate([
  92314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92315. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  92316. __decorate([
  92317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92318. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  92319. __decorate([
  92320. BABYLON.serialize()
  92321. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  92322. __decorate([
  92323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92324. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  92325. __decorate([
  92326. BABYLON.serialize()
  92327. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  92328. __decorate([
  92329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92330. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  92331. __decorate([
  92332. BABYLON.serializeAsVector3()
  92333. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  92334. __decorate([
  92335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92336. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  92337. __decorate([
  92338. BABYLON.serialize()
  92339. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  92340. __decorate([
  92341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92342. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  92343. __decorate([
  92344. BABYLON.serialize()
  92345. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  92346. __decorate([
  92347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92348. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92349. __decorate([
  92350. BABYLON.serialize()
  92351. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92352. __decorate([
  92353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92354. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92355. __decorate([
  92356. BABYLON.serialize()
  92357. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92358. __decorate([
  92359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92360. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92361. __decorate([
  92362. BABYLON.serialize()
  92363. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92364. __decorate([
  92365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92366. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92367. __decorate([
  92368. BABYLON.serialize()
  92369. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92370. __decorate([
  92371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92372. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92373. __decorate([
  92374. BABYLON.serialize()
  92375. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92376. __decorate([
  92377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92378. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92379. __decorate([
  92380. BABYLON.serialize()
  92381. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92382. __decorate([
  92383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92384. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92385. __decorate([
  92386. BABYLON.serialize()
  92387. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92388. __decorate([
  92389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92390. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92391. __decorate([
  92392. BABYLON.serializeAsImageProcessingConfiguration()
  92393. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92394. return BackgroundMaterial;
  92395. }(BABYLON.PushMaterial));
  92396. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92397. })(BABYLON || (BABYLON = {}));
  92398. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92399. "use strict";
  92400. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92401. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92402. s = arguments[i];
  92403. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92404. t[p] = s[p];
  92405. }
  92406. return t;
  92407. };
  92408. var BABYLON;
  92409. (function (BABYLON) {
  92410. /**
  92411. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92412. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92413. * It also helps with the default setup of your imageProcessing configuration.
  92414. */
  92415. var EnvironmentHelper = /** @class */ (function () {
  92416. /**
  92417. * constructor
  92418. * @param options
  92419. * @param scene The scene to add the material to
  92420. */
  92421. function EnvironmentHelper(options, scene) {
  92422. var _this = this;
  92423. this._errorHandler = function (message, exception) {
  92424. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92425. };
  92426. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92427. this._scene = scene;
  92428. this.onErrorObservable = new BABYLON.Observable();
  92429. this._setupBackground();
  92430. this._setupImageProcessing();
  92431. }
  92432. /**
  92433. * Creates the default options for the helper.
  92434. */
  92435. EnvironmentHelper._getDefaultOptions = function () {
  92436. return {
  92437. createGround: true,
  92438. groundSize: 15,
  92439. groundTexture: this._groundTextureCDNUrl,
  92440. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92441. groundOpacity: 0.9,
  92442. enableGroundShadow: true,
  92443. groundShadowLevel: 0.5,
  92444. enableGroundMirror: false,
  92445. groundMirrorSizeRatio: 0.3,
  92446. groundMirrorBlurKernel: 64,
  92447. groundMirrorAmount: 1,
  92448. groundMirrorFresnelWeight: 1,
  92449. groundMirrorFallOffDistance: 0,
  92450. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92451. groundYBias: 0.00001,
  92452. createSkybox: true,
  92453. skyboxSize: 20,
  92454. skyboxTexture: this._skyboxTextureCDNUrl,
  92455. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92456. backgroundYRotation: 0,
  92457. sizeAuto: true,
  92458. rootPosition: BABYLON.Vector3.Zero(),
  92459. setupImageProcessing: true,
  92460. environmentTexture: this._environmentTextureCDNUrl,
  92461. cameraExposure: 0.8,
  92462. cameraContrast: 1.2,
  92463. toneMappingEnabled: true,
  92464. };
  92465. };
  92466. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92467. /**
  92468. * Gets the root mesh created by the helper.
  92469. */
  92470. get: function () {
  92471. return this._rootMesh;
  92472. },
  92473. enumerable: true,
  92474. configurable: true
  92475. });
  92476. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92477. /**
  92478. * Gets the skybox created by the helper.
  92479. */
  92480. get: function () {
  92481. return this._skybox;
  92482. },
  92483. enumerable: true,
  92484. configurable: true
  92485. });
  92486. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92487. /**
  92488. * Gets the skybox texture created by the helper.
  92489. */
  92490. get: function () {
  92491. return this._skyboxTexture;
  92492. },
  92493. enumerable: true,
  92494. configurable: true
  92495. });
  92496. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92497. /**
  92498. * Gets the skybox material created by the helper.
  92499. */
  92500. get: function () {
  92501. return this._skyboxMaterial;
  92502. },
  92503. enumerable: true,
  92504. configurable: true
  92505. });
  92506. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92507. /**
  92508. * Gets the ground mesh created by the helper.
  92509. */
  92510. get: function () {
  92511. return this._ground;
  92512. },
  92513. enumerable: true,
  92514. configurable: true
  92515. });
  92516. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92517. /**
  92518. * Gets the ground texture created by the helper.
  92519. */
  92520. get: function () {
  92521. return this._groundTexture;
  92522. },
  92523. enumerable: true,
  92524. configurable: true
  92525. });
  92526. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92527. /**
  92528. * Gets the ground mirror created by the helper.
  92529. */
  92530. get: function () {
  92531. return this._groundMirror;
  92532. },
  92533. enumerable: true,
  92534. configurable: true
  92535. });
  92536. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92537. /**
  92538. * Gets the ground mirror render list to helps pushing the meshes
  92539. * you wish in the ground reflection.
  92540. */
  92541. get: function () {
  92542. if (this._groundMirror) {
  92543. return this._groundMirror.renderList;
  92544. }
  92545. return null;
  92546. },
  92547. enumerable: true,
  92548. configurable: true
  92549. });
  92550. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92551. /**
  92552. * Gets the ground material created by the helper.
  92553. */
  92554. get: function () {
  92555. return this._groundMaterial;
  92556. },
  92557. enumerable: true,
  92558. configurable: true
  92559. });
  92560. /**
  92561. * Updates the background according to the new options
  92562. * @param options
  92563. */
  92564. EnvironmentHelper.prototype.updateOptions = function (options) {
  92565. var newOptions = __assign({}, this._options, options);
  92566. if (this._ground && !newOptions.createGround) {
  92567. this._ground.dispose();
  92568. this._ground = null;
  92569. }
  92570. if (this._groundMaterial && !newOptions.createGround) {
  92571. this._groundMaterial.dispose();
  92572. this._groundMaterial = null;
  92573. }
  92574. if (this._groundTexture) {
  92575. if (this._options.groundTexture != newOptions.groundTexture) {
  92576. this._groundTexture.dispose();
  92577. this._groundTexture = null;
  92578. }
  92579. }
  92580. if (this._skybox && !newOptions.createSkybox) {
  92581. this._skybox.dispose();
  92582. this._skybox = null;
  92583. }
  92584. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92585. this._skyboxMaterial.dispose();
  92586. this._skyboxMaterial = null;
  92587. }
  92588. if (this._skyboxTexture) {
  92589. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92590. this._skyboxTexture.dispose();
  92591. this._skyboxTexture = null;
  92592. }
  92593. }
  92594. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92595. this._groundMirror.dispose();
  92596. this._groundMirror = null;
  92597. }
  92598. if (this._scene.environmentTexture) {
  92599. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92600. this._scene.environmentTexture.dispose();
  92601. }
  92602. }
  92603. this._options = newOptions;
  92604. this._setupBackground();
  92605. this._setupImageProcessing();
  92606. };
  92607. /**
  92608. * Sets the primary color of all the available elements.
  92609. * @param color
  92610. */
  92611. EnvironmentHelper.prototype.setMainColor = function (color) {
  92612. if (this.groundMaterial) {
  92613. this.groundMaterial.primaryColor = color;
  92614. }
  92615. if (this.skyboxMaterial) {
  92616. this.skyboxMaterial.primaryColor = color;
  92617. }
  92618. if (this.groundMirror) {
  92619. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92620. }
  92621. };
  92622. /**
  92623. * Setup the image processing according to the specified options.
  92624. */
  92625. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92626. if (this._options.setupImageProcessing) {
  92627. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92628. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92629. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92630. this._setupEnvironmentTexture();
  92631. }
  92632. };
  92633. /**
  92634. * Setup the environment texture according to the specified options.
  92635. */
  92636. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92637. if (this._scene.environmentTexture) {
  92638. return;
  92639. }
  92640. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92641. this._scene.environmentTexture = this._options.environmentTexture;
  92642. return;
  92643. }
  92644. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92645. this._scene.environmentTexture = environmentTexture;
  92646. };
  92647. /**
  92648. * Setup the background according to the specified options.
  92649. */
  92650. EnvironmentHelper.prototype._setupBackground = function () {
  92651. if (!this._rootMesh) {
  92652. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92653. }
  92654. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92655. var sceneSize = this._getSceneSize();
  92656. if (this._options.createGround) {
  92657. this._setupGround(sceneSize);
  92658. this._setupGroundMaterial();
  92659. this._setupGroundDiffuseTexture();
  92660. if (this._options.enableGroundMirror) {
  92661. this._setupGroundMirrorTexture(sceneSize);
  92662. }
  92663. this._setupMirrorInGroundMaterial();
  92664. }
  92665. if (this._options.createSkybox) {
  92666. this._setupSkybox(sceneSize);
  92667. this._setupSkyboxMaterial();
  92668. this._setupSkyboxReflectionTexture();
  92669. }
  92670. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92671. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92672. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92673. };
  92674. /**
  92675. * Get the scene sizes according to the setup.
  92676. */
  92677. EnvironmentHelper.prototype._getSceneSize = function () {
  92678. var _this = this;
  92679. var groundSize = this._options.groundSize;
  92680. var skyboxSize = this._options.skyboxSize;
  92681. var rootPosition = this._options.rootPosition;
  92682. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92683. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92684. }
  92685. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92686. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92687. });
  92688. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92689. if (this._options.sizeAuto) {
  92690. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92691. this._scene.activeCamera.upperRadiusLimit) {
  92692. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92693. skyboxSize = groundSize;
  92694. }
  92695. var sceneDiagonalLenght = sceneDiagonal.length();
  92696. if (sceneDiagonalLenght > groundSize) {
  92697. groundSize = sceneDiagonalLenght * 2;
  92698. skyboxSize = groundSize;
  92699. }
  92700. // 10 % bigger.
  92701. groundSize *= 1.1;
  92702. skyboxSize *= 1.5;
  92703. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92704. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92705. }
  92706. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92707. };
  92708. /**
  92709. * Setup the ground according to the specified options.
  92710. */
  92711. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92712. var _this = this;
  92713. if (!this._ground) {
  92714. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92715. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92716. this._ground.parent = this._rootMesh;
  92717. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92718. }
  92719. this._ground.receiveShadows = this._options.enableGroundShadow;
  92720. };
  92721. /**
  92722. * Setup the ground material according to the specified options.
  92723. */
  92724. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92725. if (!this._groundMaterial) {
  92726. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92727. }
  92728. this._groundMaterial.alpha = this._options.groundOpacity;
  92729. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92730. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92731. this._groundMaterial.primaryLevel = 1;
  92732. this._groundMaterial.primaryColor = this._options.groundColor;
  92733. this._groundMaterial.secondaryLevel = 0;
  92734. this._groundMaterial.tertiaryLevel = 0;
  92735. this._groundMaterial.useRGBColor = false;
  92736. this._groundMaterial.enableNoise = true;
  92737. if (this._ground) {
  92738. this._ground.material = this._groundMaterial;
  92739. }
  92740. };
  92741. /**
  92742. * Setup the ground diffuse texture according to the specified options.
  92743. */
  92744. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92745. if (!this._groundMaterial) {
  92746. return;
  92747. }
  92748. if (this._groundTexture) {
  92749. return;
  92750. }
  92751. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92752. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92753. return;
  92754. }
  92755. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92756. diffuseTexture.gammaSpace = false;
  92757. diffuseTexture.hasAlpha = true;
  92758. this._groundMaterial.diffuseTexture = diffuseTexture;
  92759. };
  92760. /**
  92761. * Setup the ground mirror texture according to the specified options.
  92762. */
  92763. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92764. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92765. if (!this._groundMirror) {
  92766. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92767. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92768. this._groundMirror.anisotropicFilteringLevel = 1;
  92769. this._groundMirror.wrapU = wrapping;
  92770. this._groundMirror.wrapV = wrapping;
  92771. this._groundMirror.gammaSpace = false;
  92772. if (this._groundMirror.renderList) {
  92773. for (var i = 0; i < this._scene.meshes.length; i++) {
  92774. var mesh = this._scene.meshes[i];
  92775. if (mesh !== this._ground &&
  92776. mesh !== this._skybox &&
  92777. mesh !== this._rootMesh) {
  92778. this._groundMirror.renderList.push(mesh);
  92779. }
  92780. }
  92781. }
  92782. }
  92783. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92784. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92785. };
  92786. /**
  92787. * Setup the ground to receive the mirror texture.
  92788. */
  92789. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92790. if (this._groundMaterial) {
  92791. this._groundMaterial.reflectionTexture = this._groundMirror;
  92792. this._groundMaterial.reflectionFresnel = true;
  92793. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92794. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92795. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92796. }
  92797. };
  92798. /**
  92799. * Setup the skybox according to the specified options.
  92800. */
  92801. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92802. var _this = this;
  92803. if (!this._skybox) {
  92804. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92805. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92806. }
  92807. this._skybox.parent = this._rootMesh;
  92808. };
  92809. /**
  92810. * Setup the skybox material according to the specified options.
  92811. */
  92812. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92813. if (!this._skybox) {
  92814. return;
  92815. }
  92816. if (!this._skyboxMaterial) {
  92817. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92818. }
  92819. this._skyboxMaterial.useRGBColor = false;
  92820. this._skyboxMaterial.primaryLevel = 1;
  92821. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92822. this._skyboxMaterial.secondaryLevel = 0;
  92823. this._skyboxMaterial.tertiaryLevel = 0;
  92824. this._skyboxMaterial.enableNoise = true;
  92825. this._skybox.material = this._skyboxMaterial;
  92826. };
  92827. /**
  92828. * Setup the skybox reflection texture according to the specified options.
  92829. */
  92830. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92831. if (!this._skyboxMaterial) {
  92832. return;
  92833. }
  92834. if (this._skyboxTexture) {
  92835. return;
  92836. }
  92837. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92838. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92839. return;
  92840. }
  92841. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92842. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92843. this._skyboxTexture.gammaSpace = false;
  92844. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92845. };
  92846. /**
  92847. * Dispose all the elements created by the Helper.
  92848. */
  92849. EnvironmentHelper.prototype.dispose = function () {
  92850. if (this._groundMaterial) {
  92851. this._groundMaterial.dispose(true, true);
  92852. }
  92853. if (this._skyboxMaterial) {
  92854. this._skyboxMaterial.dispose(true, true);
  92855. }
  92856. this._rootMesh.dispose(false);
  92857. };
  92858. /**
  92859. * Default ground texture URL.
  92860. */
  92861. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92862. /**
  92863. * Default skybox texture URL.
  92864. */
  92865. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92866. /**
  92867. * Default environment texture URL.
  92868. */
  92869. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92870. return EnvironmentHelper;
  92871. }());
  92872. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92873. })(BABYLON || (BABYLON = {}));
  92874. //# sourceMappingURL=babylon.environmentHelper.js.map
  92875. "use strict";
  92876. var BABYLON;
  92877. (function (BABYLON) {
  92878. /**
  92879. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92880. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92881. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92882. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92883. */
  92884. var VideoDome = /** @class */ (function (_super) {
  92885. __extends(VideoDome, _super);
  92886. /**
  92887. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92888. * @param name Element's name, child elements will append suffixes for their own names.
  92889. * @param urlsOrVideo
  92890. * @param options An object containing optional or exposed sub element properties:
  92891. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92892. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92893. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92894. * @param options **loop=true** Automatically loop video on end.
  92895. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92896. */
  92897. function VideoDome(name, urlsOrVideo, options, scene) {
  92898. var _this = _super.call(this, name, scene) || this;
  92899. // set defaults and manage values
  92900. name = name || "videoDome";
  92901. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92902. options.clickToPlay = Boolean(options.clickToPlay);
  92903. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92904. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92905. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92906. // create
  92907. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92908. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92909. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92910. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92911. flat: false,
  92912. radius: options.size,
  92913. subdivisions: options.resolution,
  92914. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92915. }, scene);
  92916. // configure material
  92917. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92918. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92919. material.reflectionTexture = _this._videoTexture;
  92920. material.useEquirectangularFOV = true;
  92921. material.fovMultiplier = 1.0;
  92922. // configure mesh
  92923. _this._mesh.material = material;
  92924. _this._mesh.parent = _this;
  92925. // optional configuration
  92926. if (options.clickToPlay) {
  92927. scene.onPointerUp = function () {
  92928. _this._videoTexture.video.play();
  92929. };
  92930. }
  92931. return _this;
  92932. }
  92933. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92934. /**
  92935. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92936. * Also see the options.resolution property.
  92937. */
  92938. get: function () {
  92939. return this._material.fovMultiplier;
  92940. },
  92941. set: function (value) {
  92942. this._material.fovMultiplier = value;
  92943. },
  92944. enumerable: true,
  92945. configurable: true
  92946. });
  92947. /**
  92948. * Releases resources associated with this node.
  92949. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92950. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92951. */
  92952. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92953. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92954. this._videoTexture.dispose();
  92955. this._mesh.dispose();
  92956. this._material.dispose();
  92957. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92958. };
  92959. return VideoDome;
  92960. }(BABYLON.Node));
  92961. BABYLON.VideoDome = VideoDome;
  92962. })(BABYLON || (BABYLON = {}));
  92963. //# sourceMappingURL=babylon.videoDome.js.map
  92964. 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"};
  92965. 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);
  92966. globalObject["BABYLON"] = BABYLON;
  92967. 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 ;
  92968. 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 };